Chinaunix

标题: Project Euler - 002 [打印本页]

作者: icymirror    时间: 2015-09-25 09:41
标题: Project Euler - 002
本帖最后由 icymirror 于 2015-09-25 09:42 编辑

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.

问题2:
斐波那契数列中的每一项都是由它之前两项求和得到的。当以1和2开始时,开始10项是:1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ......
现在,把此数列中的数值不超过4000000的项中的偶数求和,结果是多少?

代码:
  1. package main

  2. import (
  3.         "fmt"
  4. )

  5. func Problem002(scope int) int {
  6.         sum := 0

  7.         first := 1
  8.         second := 2
  9.        
  10.         for {
  11.                 if (second > scope) {
  12.                         break
  13.                 }
  14.                
  15.                 sum = sum + second

  16.                 first, second = first + second * 2, first * 2 + second * 3
  17.         }
  18.        
  19.         return sum
  20. }

  21. func main() {
  22.         fmt.Println("Problem 002 result: ", Problem002(4000000))
  23. }
复制代码

作者: ba_du_co    时间: 2015-10-09 14:18
拿来练练手。
4613732
  1. #!perl6
  2. my $n = 4000000;
  3. say [+] (1, 2, *+* ...^ * > $n).grep: * %% 2
复制代码





欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2