不知不觉,欧拉项目就零零碎碎的做了15道题了,觉得真是非常的花时间,但是依然还是乐此不彼。下面奉上欧拉项目第二题代码
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, ... Find the sum of all the
even-valued terms in the sequence which do not exceed four million.
这道题算法不难,主要点在于审题。可能是我英语不太好吧,开始做了好久都没有做出来,我还以为是我算法出了问题,后来验证了很多遍都没有什么问题。然后仔细去看了下题目, even-valued是什么意思。一看,原来是偶数,顿时恍然大悟。简单的修改了一下代码,即可求得正解。代码如下:
public class Problem2 { public static void main(String[] args) { long a = 1; long b = 1, c; long sum = 0; while (b < 4000000) { b = a + b; a = b - a; if (a % 2 == 0) { sum += a; } } System.out.println(a); System.out.println(sum); } }