public class assignment6part3 {
public static void main(String[] args) {
int q = 0;
for ( int count=1; count <= 10000; count++) {
if (Prime(count)) {
q = q + 1;
}
}
System.out.println("It comes out " + q + " times.");
}
public static boolean Prime(int n) {
if (n <= 1) {
return false;
}
for (int i = 1; i < Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
我试图获取 0 到 10000 之间的素数数量,但是当我运行它时,它说有 0 个素数。代码的哪一部分导致了此错误?
最佳答案
在你的函数中Prime
你的for
循环运行如下::
for(int i = 1; i < Math.sqrt(n); i++)
,从i = 1
开始每个数字都可以被1
整除因此0
质数..:P
i
的初始化条件应为i = 2
您可能考虑更改的其他事项::
for (int i = 1; i < Math.sqrt(n); i++)
应更改为
for (int i = 1; i <= Math.sqrt(n); i++)
注意::寻找素数的更佳方法是 https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
关于java - 初学者我的方法有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31690288/