java获取素数
请看一下下面的代码
public class Prime
{
public static void main(String[]args)
{
int i = 2;
int counter = 0;
while(true)
{
if(counter==6)//Count still 6
{
break;
}
else
{
if(getPrimes(i)==true)
{
i++;
counter++;
System.out.println("Counter: "+counter);
}
else
{
System.out.println("No");
}
}
}
}
static boolean getPrimes(int num)
{
boolean result = false;
int i = 2;
while(true)
{
if((num%i) != 0) //if the number cannot be divided by any other number (except 1 and it self) it is prime
{
result = true;
System.out.println(num);
System.out.println("I is: "+i);
i=2;
break;
}
else //Not a prime. Repeat the process
{
result = false;
i++;
}
}
return result;
}
}
在这里,我试图得到0-6之间的所有素数。这是从一个非常大的数字中得到数千个素数的测试用例。然而,它并不是只显示素数,而是显示每一个数字
我做错了什么?请帮忙
# 1 楼答案
使用筛子Eratosthenes或Atkins
下面是Robert Sedgewick在Java中的Eratosthenes实现:
http://introcs.cs.princeton.edu/java/14array/PrimeSieve.java.html
# 2 楼答案
它将显示所有素数
# 3 楼答案
我想你需要这样的东西:
# 4 楼答案
用最小迭代法求素数
布尔IsPrimeNumber(int num){
# 5 楼答案
我想我找到了解决办法。至少,我找到了我需要的答案。这是我的答案
我想这是最简单的方法
# 6 楼答案
试试这个答案。。。在你的回路中