论坛首页 Java企业应用论坛

ProjectEuler第二题

浏览 1485 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2011-05-24   最后修改:2011-05-24
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;
	}
}
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics