gpt4 book ai didi

java - 欧拉计划编号2

转载 作者:太空宇宙 更新时间:2023-11-04 08:08:17 25 4
gpt4 key购买 nike

我尝试了很多次,但我似乎无法弄清楚我做错了什么。这是我最近尝试的解决方案之一。

我从其他来源知道正确答案是4613732

/*
* 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.
*/

public class problem2
{
public static void main(String args[])
{
int sum = 0;

int[] anArray = new int[4000000];
anArray[0] = 1;
anArray[1] = 2;

for (int i = 2; i <= anArray.length - 1; i++) {
anArray[i] = anArray[i - 1] + anArray[i - 2];

if (anArray[i] % 2 == 0 && anArray[i] <= 4000000) {
sum += anArray[i];
}
}
System.out.println(sum);
}
}

最佳答案

首先,你缺少两个其次,为了避免溢出问题:http://en.wikipedia.org/wiki/Integer_overflow ,一旦超过一百万,就应该插入一个break语句。

关于java - 欧拉计划编号2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11706716/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com