繁体   English   中英

创建一个斐波那契数列,找到所有奇数的总和

[英]Creating a Fibonacci sequence, finding sum of all odd numbers

我正在尝试创建一个斐波那契数列,从 1 和 2 开始,到 1000 结束。那部分我已经弄清楚了,但它还需要返回所有奇数的总和。 我以为我明白了,但我不断得到不正确的结果。

这是我的代码,感谢我能得到的任何帮助。

public class Fibonacci {
    public static void main(String[] args) {
        int n = 1000, t1 = 1, t2 = 2, odd = 0;
        
        System.out.print("Fibonacci to " + n + ": ");
        while (t1 <= n)
        {
            System.out.print(t1 + " + ");

            int sum = t1 + t2;
            t1 = t2;
            t2 = sum;
            if (t1 % 2 != 0)
                odd = odd + t1;
        }
        System.out.print("All odd numbers combined are: " + odd);
    }
}

您正在跳过算法中的值。

在将当前t1值添加到odd之前,将其更新为下一个。

斐波那契数列是:

t1  t2  t1  t2  t1  t2   t1   t2
1   2   3   5   8   13   21   34

您之前不是添加 1,而是将t1更新为 3,因此忽略 1。

在你的while循环中,试试这个:

System.out.print(t1 + " + ");

if (t1 % 2 != 0) odd += t1;
t2 += t1;
t1 = t2 - t1;

因为我看到其他人提供了一个不错的答案,所以我喜欢使用 List<>、Streams 和递归来制作其他东西。 你说你对编程很陌生,所以不要犹豫,问我的代码发生了什么。 虽然我主要是通过谷歌搜索自己学习的。

public class Fibonacci {

    private static final List<Integer> oddNumbers = new ArrayList<>();

    public static void main(String[] args) {

        generateFibonacciSequence(1000).forEach(number -> {
            if (number < 1000){
                System.out.println(number);

                if (number % 2 != 0){
                    oddNumbers.add(number);
                }
            }
        });
        System.out.println("sum of odd numbers = " + oddNumbers.stream().mapToInt(oddNumber -> oddNumber).sum());
    }

    public static IntStream generateFibonacciSequence(int limit) {
        AtomicInteger number = new AtomicInteger(0);
        return IntStream.generate(
                () -> fibonacci(number.incrementAndGet()))
                .takeWhile((numberValue -> numberValue < limit));
    }

    private static int fibonacci(int position) {
        if (position == 1 || position == 2) {
            return 1;
        }
        return fibonacci(position - 2) + fibonacci(position - 1); //recursion
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM