我有以下代码在1和N之间吐出素数。一位朋友提出了这个解决方案,但我相信有一种更有效的方法来编写这段代码。比如if (i%j!=0) {System.out.print (i + " ");}
。但是我发现这个地方随机出现了数字......
import java.util.Scanner;
public class AllPrime {
public static void main(String[] args) {
System.out.println("Enter a number:\n");
Scanner input = new Scanner(System.in);
int a = input.nextInt();
for (int i = 2; i < a; i++) {
boolean primeNum = true;
for(int j=2; j<i; j++) {
if (i%j==0) {
primeNum =false;
}
}
if (primeNum) {
System.out.print(i + " ");
}
}
}
}
答案 0 :(得分:4)
查看适当的筛子,例如Sieve of Eratosthenes。您无需每次都检查%
。
答案 1 :(得分:1)
for(int j=2; j<i; j++) {
if (i%j==0) {
primeNum =false;
}
}
这不是一个非常有效的算法,但至少要在其中放一个break
......
答案 2 :(得分:1)
public static boolean [] createPrimes (final int MAX)
{
boolean [] primes = new boolean [MAX];
// Make only odd numbers kandidates...
for (int i = 3; i < MAX; i+=2)
{
primes[i] = true;
}
// ... except No. 2
primes[2] = true;
for (int i = 3; i < MAX; i+=2)
{
/*
If a number z is already eliminated
(like No. 9), because it is a multiple of -
for example 3, then all multiples of z
are already eliminated.
*/
if (primes[i] && i < MAX/i)
{
int j = i * i;
while (j < MAX)
{
if (primes[j])
primes[j] = false;
j+=2*i;
}
}
}
return primes;
}
Will Ness评论后将速度提高到大约2/1,它在我的2Ghz单核上检查5s内的1亿个英寸。
答案 3 :(得分:-1)
private static void generatePrimes(int maxNum) {
boolean[] isPrime = new boolean[maxNum + 1];
for (int i = 2; i <= maxNum; i++)
isPrime[i] = true;
// mark non-primes <= N using Sieve of Eratosthenes
for (int i = 2; i * i <= Math.sqrt(maxNum); i++) {
// if i is prime, then mark multiples of i as nonprime
if (isPrime[i]) {
for (int j = i; i * j <= maxNum; j++)
isPrime[i * j] = false;
}
}
// count primes
int primes = 0;
for (int i = 2; i <= maxNum; i++)
if (isPrime[i]) {
System.out.println("Prime - " + i);
primes++;
}
System.out.println("The number of primes <= " + maxNum + " is "+ primes);
}