计算非负数下的质数数-JAVA

时间:2018-07-23 03:07:56

标签: java boolean primes

我写出代码来查找非负数下的质数,不知道这段代码有什么问题: -当我n = 10时,我的输出是4,这是正确的。 (2,3,5,7)-10以下的质数 -当我n = 10000时,我的输出是3334,而我的输出应该是1229。 不知道这段代码出了什么问题,我花了很多时间来分析它。

public static void main(字符串[] args){

    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;
}

2 个答案:

答案 0 :(得分:1)

素数的概念:素数是大于1的自然数,不是两个较小数的乘积。

也许这就是您想要的:

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,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]

答案 1 :(得分:0)

用以下代码替换isPrime函数:

boolean isPrime(int n) {
  //check if n is a multiple of 2
  if (n%2==0) return false;
  //if not, then just check the odds
  for(int i=3;i*i<=n;i+=2) {
    if(n%i==0)
        return false;
  }
  return true;
}

我从here得到了这个解决方案。基本上,如果一个数字不能被二整除,则其他任何偶数都不能将其整除。因此,只需检查一下是否可以将其除以任何奇数即可。这将产生正确的答案,并将您的搜索时间缩短一半。