Printing prime numbers from 1 through 100

前端 未结 22 2525
无人共我
无人共我 2020-11-28 05:14

This c++ code prints out the following prime numbers: 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97.

But I don\'t think tha

22条回答
  •  时光说笑
    2020-11-28 06:00

    Using Sieve of Eratosthenes logic, I am able to achieve the same results with much faster speed.

    My code demo VS accepted answer.

    Comparing the count, my code takes significantly lesser iteration to finish the job. Checkout the results for different N values in the end.

    Why this code performs better than already accepted ones:

    - the even numbers are not checked even once throughout the process.

    - both inner and outer loops are checking only within possible limits. No extraneous checks.

    Code:

    int N = 1000; //Print primes number from 1 to N
    vector primes(N, true);
    for(int i = 3; i*i < N; i += 2){    //Jump of 2
        for(int j = 3; j*i < N; j+=2){  //Again, jump of 2
            primes[j*i] = false;
        }
    }
    if(N >= 2) cout << "2 ";
    for(int i = 3; i < N; i+=2){        //Again, jump of 2
        if(primes[i] == true) cout << i << " "; 
    }
    

    For N = 1000, my code takes 1166 iterations, accepted answer takes 5287 (4.5 times slower)

    For N = 10000, my code takes 14637 iterations, accepted answer takes 117526 (8 times slower)

    For N = 100000, my code takes 175491 iterations, accepted answer takes 2745693 (15.6 times slower)

提交回复
热议问题