【发布时间】:2015-09-28 03:46:03
【问题描述】:
我试图在给定数组中找到我们所有的素数。为此,我编写了以下代码。不知何故,它没有按预期工作。 请帮我调试问题。
public class primenbr {
public static void main(String[] args) {
int a[]= { -2,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97};
int Prime_flag=0;
//for loop to keep going one by one and to check if the number is prime
System.out.println("welcome to Basic prime number program");
for(int j=0;j<=99 & a[j] > 1;j++) {
Prime_flag=0;
//checks for prime number
for(int i=2,div=(int) Math.sqrt(a[j]) + 1; i <= div;i++){
if (a[j]%i==0){
Prime_flag++;
}
}
if ((Prime_flag == 0 & a[j] >= 2) | a[j] == 2)
System.out.println("Hurray!!! This is a prime number"+a[j]);
}
}
}
输出:
欢迎来到基本素数程序
【问题讨论】:
-
你有什么问题?
-
你认为你的代码应该如何工作,你为什么这么认为?
-
对不起,我是这个论坛的新手。我的问题在下面的代码 System.out.println("welcome to Basic prime number program"); for(int j=0;j 1;j++) 为什么它没有进入这个 for 循环,尽管我在每次迭代后都会增加 J 的值。
-
调试是你的朋友。
标签: java for-loop conditional-statements