`
linuke
  • 浏览: 10134 次
  • 性别: Icon_minigender_1
  • 来自: 随州
社区版块
存档分类
最新评论

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  c
		while(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;
	}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics