[ProjectEuler.net] 14

來源:互聯網
上載者:User

n按照下面的規則產生的序列:

n  n/2 (n is even)
n  3n + 1 (n is odd)

比如13:

13  40  20  10  5  16  8  4  2  1 求在100萬以下的數中,哪個數產出的序列最長。產出的序列中會包含很多以前計算過的,所以要緩衝起來,以下使用了字典。要注意的是當一個數很大的時候,如果是奇數,那麼下一個數可能會超出類型的最大值。所以以下F#就用int64了其實下面代碼是haskell直接轉型過來的,唉,haskell怎麼寫才快起來呢..
let isEven (n:int64) =
n % 2L = 0L

let next n=
match isEven n with
| true -> n/2L
| false -> 3L*n+1L


open System.Collections.Generic

let dict =new Dictionary<int64 ,int64 list>()

let rec gen (n:int64)=
if n =1L then [1L]
elif dict.ContainsKey n then dict.[n]
else
let x =gen<| next n in
dict.Add(n,n::x)
n::x

let mapToLen xs =
List.map (fun x->
let xs = gen x
match xs with
| h:: t->(h, List.length xs)) xs

List.maxBy (fun (v,l)->l) <| mapToLen [1L..1000000L]

--haskell
import qualified Data.Map as Map

longlength ::[a] -> Integer
longlength =fromIntegral . length

isEven :: Integer -> Bool
isEven x
| x `mod`2 == 0 = True
| otherwise =False

next :: Integer -> Integer
next n
| isEven n =n `div` 2
| otherwise =3*n+1
tree =Map.empty
--使用Map緩衝
gen' :: Integer ->Map.Map Integer [Integer] -> ([Integer],Map.Map Integer [Integer])
gen' 1 t =([1],t)
gen' n t =
case Map.lookup n t of
Just v -> (v,t)
Nothing ->(ret,Map.insert n ret t')
where (nxts,t') =gen' (next n) t
ret =n:nxts

mapToLen:: [Integer]->Map.Map Integer [Integer]->[Integer]
mapToLen [] t =[]
mapToLen (x:xs) t =
let (lst,t')=gen' x t in
(longlength lst):mapToLen xs t'
--Ghci中 maximum $ rang 1 1000000
range a b =
mapToLen [a.. b] tree


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.