如何在素数斐波那契数字旁边打印文本通知?
问题描述:
这是一门12年级计算机科学课的作业。如何在素数斐波那契数字旁边打印文本通知?
我有困难的任务的部分内容如下:
确定第一20张斐波那契数是素数。
在基本挑战打印输出中放入“这是主要”文本通知。
将FibPrimes存储在名为FibPrimes的数组中。
以下是我已经尝试:
接近底部,我试图做一个循环,将打印文本的通知“这是一个最好的”如果给定FibNum元素是等于FibPrime元件。这没有奏效。 问题块通过评论标识。程序的其余部分没问题。
package fibonaccinumbers;
public class FibonacciNumbers {
public static void main(String[] args) {
// Creation of Fibonacci Numbers Array.
int [] FibNums = new int[20];
FibNums[0] = 0;
FibNums[1] = 1;
// Creation if Fibonacci Primes Array.
int [] FibPrimes = new int[7];
FibPrimes[0] = 2;
FibPrimes[1] = 3;
FibPrimes[2] = 5;
FibPrimes[3] = 13;
FibPrimes[4] = 89;
FibPrimes[5] = 233;
FibPrimes[6] = 1597;
// Printing first two fibonacci numbers.
System.out.println(0);
System.out.println(1 + "*");
// Printing remaining fibonacci numbers up to 20th term.
for (int i=2; i<FibNums.length;i++){ // Begin number generation loop.
FibNums[i] = FibNums[i-1] + FibNums[i-2];
// Checks if the fibonacci number is odd.
// A number is not odd if two divides into it evenly.
boolean oddcheck = true;
if (FibNums[i]%2==0){
oddcheck = false;
}
// Prints odd fibonacci numbers with a star beside it.
// Prints even fibonacci numbers with no star beside it.
if (oddcheck == true){
System.out.println(FibNums[i] + "*");
} else {
System.out.println(FibNums[i]);
}
// PROBLEM BLOCK HERE. ************************
// If any element in the FibPrimes array is equal to the FibNums
// array, then the number is a prime.
for (int n=0; n<=FibPrimes.length; n++){
if (FibNums[i] == FibPrimes[n]){
System.out.print(" " + "This is a prime.");
}
}
} // End number generation loop.
}
}
输出与问题块移除:
0
1*
1*
2
3*
5*
8
13*
21*
34
55*
89*
144
233*
377*
610
987*
1597*
2584
4181*
(星星识别奇数 - 从分配的不同部分)
输出与问题块剩余:
0
1*
1*
请注意,其余数字不打印,也没有文字通知。
有可能有更好的方法来解决这个问题比我目前有,但我会继续修改这个。让我知道你是否需要更多信息。谢谢。
谢谢@AJNeufeld和@YayPawSi。使用您的解决方案,我能够打印出程序。 修订输出:
0
1*
1*
This is a prime. 2
This is a prime. 3*
This is a prime. 5*
8
This is a prime. 13*
21*
34
55*
This is a prime. 89*
144
This is a prime. 233*
377*
610
987*
This is a prime. 1597*
2584
4181*
答
这是ArrayIndexOutOfBoundException,
//Remove = sign for n < FibPrimes.length
for (int n = 0; n < FibPrimes.length; n++){
if (FibNums[i] == FibPrimes[n]){
System.out.print(" " + "This is a prime.");
}
}
欢迎堆栈溢出!由于循环'for(int n = 0; n AJNeufeld
我很确定你的任务并不指望你预先计算出主要斐波那契数,并将它们存储到数组中(就像你所做的那样)。我敢肯定,你应该*计算*斐波那契数是否为素数,如果是的话,将它存储在FibPrimes中。 –
@StephenC感谢您的评论。你绝对正确,我也这么认为。由于任务的困难,我的首要任务是创造一些“功能”。这将是我的下一个目标。 –