java - 计算非负数下的素数个数 - JAVA
问题描述
我写了代码来查找非负数下的素数个数,不确定这段代码有什么问题: - 当我 n = 10 时,我的输出是 4,这是正确的。(2,3,5,7) - 10 以下的素数 - 当我 n = 10000 时,我的输出是 3334,而应该是 1229。不知道这段代码哪里出错了,我花了很多时间分析它.
公共静态无效主要(字符串[]参数){
int n = 10000;
int counter = 0;
if (n <= 2) {
System.out.println("0 prime numbers"); }
if (n == 3) {
System.out.println("1 prime number"); }
counter+=2; //accounts for prime numbers 2 and 3
for (int x = 4; x < n; x++) {
//Started at 4 since I have already checked for 2 and 3
if (isPrime(x) == true) {
counter = counter + 1; }
}
System.out.println("The number of prime numbers are " + counter); }
public static boolean isPrime (int x) {
if (x % 2 == 0 || x % 3 == 0) {
return false; }
return true;
}
解决方案
素数的概念:素数是大于一的自然数,不是两个较小数的乘积。
也许这就是你想要的:
public static boolean isPrime(List<Long> primes, long number) {
if(number < 2) return false;
for (Long prime : primes) {
if (number % prime == 0) return false;
}
return true;
}
public static void main(String[] args) {
List<Long> primes = new ArrayList<>();
long max = 10000;
long num = 2;
while(num < max) {
if(isPrime(primes, num)) {
primes.add(num);
}
num++;
}
System.out.println("count: " + primes.size());
System.out.println("primes: " + primes);
}
上面代码的输出:
计数:1229
素数: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89 , 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227 , 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373 , 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523 , 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683 , 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859 , 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, ....
9613, 9619, 9623, 9629, 9631, 9643, 9649, 9661, 9677, 9679, 9689, 9697, 9719, 9721, 9733, 9739, 9743, 9749, 9767, 9769, 9781, 9787, 9791, 9803, 9811, 9817、9829、9833、9839、9851、9857、9859、9871、9883、9887、9901、9907、9923、9929、9931、9941、9949、9967、9973]
推荐阅读
- python-3.x - 为什么有效的 PDF 链接返回状态码 404?
- sql - 算术溢出错误:消息 8115,级别 16,状态 2
- javascript - 角度绑定值到编辑器
- mercurial - Mercurial 的所有内置提交标识符是什么?
- text - Tmux 不使用 gnome-terminal 调色板
- node.js - 如何在 express-validator 中设置小数的最小值
- c# - 如何为多个转换编写 Iconverter
- python - socket.emit 延迟在 flask_SocketIO 中不起作用
- docker - 在一个 Dockerfile 中对 next.js 和 nginx 进行 Dockerize
- php - Dynamics Crm 在展开时应用过滤器