使用 Flag 方法替换斐波那契数列中的数字倍数

Replacing Multiples of numbers in Fibonacci series using Flag method

如标题所示,我有斐波那契数列的代码,我的目标是用一个词替换该数列中的多个数字(3、5、7 及其组合)。有人建议我在 if 循环中使用一个标志来检查打印的短语,如果打印了该短语,则跳过该数字。本质上,我希望输出看起来像:

1 1 2 跳过 8 13 跳过 34 55

(目前仅替换三的倍数)。

相反,我得到的是:

1 1 2 3 跳过 5 8 13 21 跳过 34 55

这是我目前的代码:

int febCount = 50;
long[] feb = new long[febCount];
feb[0] = 1;
feb[1] = 1;
for (int i = 2; i < febCount; i++) {
 feb[i] = feb[i - 1] + feb[i - 2];
}

for (int i = 0; i < febCount; i++) {
 System.out.print(feb[i] + ((i % 10 == 9) ? "\n" : " "));
 if (feb[i] % 3 == 0)
  System.out.print("skip");
}

感谢任何帮助!

让我们浏览一下您提供的代码并尝试了解它为什么不起作用。

//The first thing we do is setup the loop to iterate through the fib numbers.
//This looks good.
for (int i = 0; i < febCount; i++) {
 //Here we print out the fibonacci number we are on, unconditionally.
 //This means that every fibonacci number will be printed no matter what number it is
 //we don't want that.
 System.out.print(feb[i] + ((i % 10 == 9) ? "\n" : " "));
 //After we print the number, we check to see if it is a multiple of three.
 //maybe we should be waiting to print until then?
 if (feb[i] % 3 == 0)
  System.out.print("skip");
}

既然我们已经遍历了代码,我们可以提出一个新的解决方案。 让我们尝试更新循环,让它等待打印斐波那契数,直到我们检查它是否满足我们的条件。

for (int i = 0; i < febCount; i++) {
    if (feb[i] % 3 == 0 || feb[i] % 5 == 0 || feb[i] % 7 == 0) { //check if multiple of 3 5 or 7
         System.out.println(" Skip ");
    } else { //if it's not a multiple, then print the number
       System.out.println(" " + feb[i]);
    }
}