我已经用java完成了该程序,但它没有按预期工作。我想找到素数(不使用构造函数或方法)并将它们存储在数组中,但结果不同。
public class Prime {
public static void main(String []args){
int s[]=new int[100];
for (int i=3;i<=100;i++){
int c=0;
for (int j=1;j<=i;j++){
if (i%j==0){
c++;
}
}
if (c<3){
for (int a=0;a<s.length;a++){
s[a]=i;
}
}
}
for (int b=0;b<s.length;b++){
System.out.println(s[b]);
}
}
}
预计: 3 5 7 。 。 。 97
输出得到:
最佳答案
错误在这里:
for (int a=0;a<s.length;a++){
s[a]=i;
}
每当您找到质数时,请将 s
的每个元素设置为该数字,这意味着最终 s
将被填充与你找到的最后一个素数 - 97。
不要用找到的素数填充数组,而是声明一个名为 next
的新变量,用于跟踪下一个素数应该在数组中的位置:
int s[]=new int[100];
int next = 0; // the first prime should go in index 0
for (int i=3;i<=100;i++){
int c=0;
for (int j=1;j<=i;j++){
if (i%j==0){
c++;
}
}
if (c<3){
s[next] = i; // put it in next
next++; // the next prime should go in the next index
}
}
for (int b=0;b<next;b++){ // only loop to "next", because the indices past "next" are not set
System.out.println(s[b]);
}
关于java - 我想存储从 3 到 100 的素数并将它们存储在数组中而不使用构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57230752/