java - 欧拉计划 #2 无限?

标签 java fibonacci

我正在尝试解决 Euler's Project #2我一直得到“无限”或“NaN”(不是数字)的答案 我尝试将数字类型更改为 int(最初是 Double),但是没有解决任何问题只是给了我答案“-1833689714”

public class Pro {
    static int g = 1;
    static int n, f = 0;
    public static void main(String args[]) {
        for (int i = 0; i <= 4000000; i++) {
            f = f + g;
            g = f - g;
            if (f % 2 == 0) {
                n += f;
            }
        }
        System.out.println("Answer: " + n);
    }
}

问题是:

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.

最佳答案

您考虑的是斐波那契数列的前 4,000,000 项,而不是不超过 4,000,000 的前 x 项。

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

相关文章:

python - 斐波那契与 Python : IndexError: list index out of range

python - 我们可以使用 pandas 数据框使用先前的值计算下一个值吗?一个很好的例子是斐波那契数列

c - 斐波那契数列之和

c - C 中的斐波那契算法——为什么它可以作为返回值?

java - 具有百分比高度和宽度的相对布局

java - 关于 ServletConfig 实例化的简单 Servlet 问题

java - 为什么我的程序连续输出两次结果?

c# - 测试 spy 实现之间的差异

python - 斐波那契数列计算器似乎是正确的,但无法在网上找到类似的代码。有什么不对?

java - 无法使用 WebFlux 在 Spring Boot 中使用 H2 和 R2DBC 创建 ConnectionFactory 错误