-
答案 1:
抱歉刚才看成40000了,原来是4百万
那个projectEuler哪里能看到答案啊,看题目貌似是求偶数和
haskell代码:
problem2 = sum $ filter (even) $ takeWhile(<4000000) myfiblist
where myfiblist = 0 : 1 : zipWith (+) myfiblist (tail myfiblist)
答案4613732
where后面那个myfiblist生成一个fibonacci数的无限列表
takeWhile(<40000) 取出其中<40000的
filter (even)取出其中的偶数
sum就是sum一下
-
答案 2:
当然使用递归。 循环一般分两种计算,一种是根据一个序列得到另一个序列,对每一个元素进行一定的操作。也就是像map那样: map f (x:xs) = (f x): map f xs map f [ ] = [ ] 所以平常使用map就行了。 另一种是根据一个序列计算一个结果,就像fold一样(这里用foldl说明): foldl f a [ ] = a foldl f a (x:xs) = fold f (f a x) xs 所以平常用fold就行了。
比如: sum = 1; pre_num = 1; num = 2; while num <= 40000 if num%2 == 0 then sum += num [num, pre_num] = [num+pre_num, num]
console.log sum
原题: projecteuler.net/problem=2
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.