Printing out Prime Numbers from 2 to 1000

后端 未结 5 722
萌比男神i
萌比男神i 2020-12-21 19:01

I am writing a code that write all the prime numbers from 2 to 1000 in a file, named primes.txt. For some reason I am not able to figure out the correct way to do this probl

相关标签:
5条回答
  • 2020-12-21 19:31

    Change your for condition in checkIfPrime(int num) to

    for (int i = 2; i < num; i++) {
    

    BTW if (checkIfPrime(i) == true){ can be written as if (checkIfPrime(i)){

    0 讨论(0)
  • 2020-12-21 19:38

    A number num is prime if it's not divisible by any other number that is greater than one and smaller than num. Where is this in your code? :-)

    0 讨论(0)
  • 2020-12-21 19:38

    Here's how you could "hard-code" an incremental sieve of Eratosthenes on a 2-3-5-7 wheel to print the primes up to 1000. In C-like pseudocode,

    primes_1000()
    {
       // the 2-3-5-7 wheel
       int wh[48] = {10,2,4,2,4,6,2,6,4,2,4,6,6,2,6,4,2,6,4,6,8,4,2,4,
                      2,4,8,6,4,6,2,4,6,2,6,6,4,2,4,6,2,6,4,2,4,2,10,2};
       // core primes' multiples, each with its pointer into the wheel
       int m[7][4] = { {1,11,11,11*11}, {2,13,13,13*13}, {3,17,17,17*17},
                       {4,19,19,19*19}, {5,23,23,23*23}, {6,29,29,29*29},
                       {7,31,31,31*31} };    // 23*23 = 529 
       int i=1, p=11, k=0;
       print(2); print(3); print(5); print(7);
       p = 11;             // first number on the wheel - the first candidate
       do {
          // the smallest duplicate multiple is 121*13, ==> no dups below 1000!
          for( k=0; k < 7; ++k) {
             if ( p == m[k][3] ) {             // p is a multiple of m[k][1] prime:
                m[k][2] += wh[ m[k][0]++ ];    //   next number on the wheel
                m[k][3]  = m[k][1] * m[k][2];  //   next multiple of m[k][1] 
                m[k][0] %= 48;                 //   index into the wheel
                break;
             }
          }
          if (k == 7) {    // multiple of no prime below 32 -
              print(p);    //   - a prime below 1000!   (32^2 = 1024)
          }
          p += wh[i++];    // next number on the candidates wheel
          i %= 48;         // wrap around to simulate circular list
       } while ( p < 1000 );
    }
    

    For primes below 500, only 4 sieve variables need to be maintained, for the additional core primes {11,13,17,19} above the wheel's inherent primes 2,3,5,7.

    (see also Printing prime numbers from 1 through 100).

    m is the dictionary of base primes and their multiples on the wheel (multiplesOf(p) = map( multiplyBy(p), rollWheelFrom(p) ), each with its own index into the wheel. It should really be a priority queue, min-ordered by the multiples' values.

    For a true unbounded solution a separate primes supply can be maintained, to extend the dictionary prime by prime when the next prime's square is reached among the candidates.

    0 讨论(0)
  • 2020-12-21 19:39

    calculation can be made even faster by checking the division with prime numbers only. Any non prime number is divisible by some prime number smaller than itself.

        static List<Integer> primes = new ArrayList<Integer>();
    
    public static void main(String[] args) {
        for (int i = 2; i < 10000; i++) {
            if(checkPrime(i)){
                primes.add(i);
            }
        }
        System.out.println(primes);
    }
    
    private static boolean checkPrime(int n) {
        for (Integer i : primes) {
            if(i*i > n ){
                break;
            }else if(n%i==0 )
                return false;
         }
        return true;
    }
    
    0 讨论(0)
  • 2020-12-21 19:47

    What happens when you pass in your first number, 2, to checkIfPrime? It will take remainder of 2 divided by 2, which is 0, falsely claiming that 2 is not prime.

    You need to stop testing remainders before you actually get to num. Stop your i for loop before i gets to num. (In fact, you can stop after i has reached the square root of num).

    for (int i = 2; i < num; i++){
    

    or even

    for (int i = 2; i <= Math.sqrt(num); i++){
    

    If you're feeling adventurous, you may try implementing the Sieve of Eratosthenes, which marks all composite numbers up to an arbitrary limit (in this question, 1000). Then you just print out the rest of the numbers -- the primes.

    0 讨论(0)
提交回复
热议问题