Most efficient code for the first 10000 prime numbers?

前端 未结 30 1403
日久生厌
日久生厌 2020-11-29 19:09

I want to print the first 10000 prime numbers. Can anyone give me the most efficient code for this? Clarifications:

  1. It does not matter if your code is ineffici
30条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-29 19:42

    Since you want first 10000 primes only, rather than coding complex algorithm I'll suggest the following

    boolean isPrime(int n){
    //even but is prime
        if(n==2)
            return true;
    //even numbers filtered already 
        if(n==0 || n==1 || n%2==0)
            return false;
    
    // loop for checking only odd factors
    // i*i <= n  (same as i<=sqrt(n), avoiding floating point calculations)
        for(int i=3 ; i*i <=n ; i+=2){
        // if any odd factor divides n then its not a prime!
            if(n%i==0)
                return false;
        }
    // its prime now
        return true;
    }
    

    now call is prime as you need it

    for(int i=1 ; i<=1000 ; i++){
        if(isPrime(i)){
           //do something
        }
    }
    

提交回复
热议问题