首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

ProjectEuler其次题

2012-11-05 
ProjectEuler第二题By considering the terms in the Fibonacci sequence whose values do not exceed fou

ProjectEuler第二题
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

求Fibonacci数列(1,2,3,5,8,……)中所有小于4000000的偶数的和。

public class Task_2 {/** * 求Fibonacci数列(1,2,3,5,8,……)中所有小于4000000的偶数的和。 * @param args */public static void main(String[] args) {System.out.println(sum1());System.out.println(sum2());}public static int sum1(){int limit = 4000000 ;int sum = 0;int a = 1;int b = 1;int c;//1 1 2 3 5 8 13 21 34 55 89 144 ...//a b c a b c a  b  c  a  b  cwhile(b<limit){if(b%2 == 0){sum += b;}c = a+b;a = b;b = c;}return sum;}public static int sum2(){int limit = 4000000 ;int sum = 0;int a = 1;int b = 1;int c = a + b;while(b<limit){//2 8 34 144...sum += c;a = b + c;b = a + c;c = a + b;}return sum;}}

热点排行