Printing prime numbers from 1 through 100

前端 未结 22 2339
无人共我
无人共我 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 05:59

    It's fine to change your for loop to for (int j=2; j<=sqrt(i); j++) but then you also need to change something else. Looking specifically at your print condition,

    else if (i == j+1) {
          cout << i << " ";
    }
    

    why will that never be triggered if you only iterate up to sqrt(i)? Where can you move the cout to to change this? (Hint: you may want to move the print out of the loop and then make use of some type of flag variable)

    0 讨论(0)
  • 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<bool> 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)

    0 讨论(0)
  • 2020-11-28 06:00
    #include<iostream>
    using namespace std;
    void main()
    {
            int num,i,j,prime;
        cout<<"Enter the upper limit :";
        cin>>num;
        cout<<"Prime numbers till "<<num<<" are :2, ";
    
        for(i=3;i<=num;i++)
        {
            prime=1;
            for(j=2;j<i;j++)
            {
                if(i%j==0)
                {
                    prime=0;
                    break;
                }
            }
            if(prime==1)
                cout<<i<<", ";
        }
    }
    
    0 讨论(0)
  • 2020-11-28 06:01

    Three ways:

    1.

    int main () 
    {
        for (int i=2; i<100; i++) 
            for (int j=2; j*j<=i; j++)
            {
                if (i % j == 0) 
                    break;
                else if (j+1 > sqrt(i)) {
                    cout << i << " ";
    
                }
    
            }   
    
        return 0;
    }
    

    2.

    int main () 
    {
        for (int i=2; i<100; i++) 
        {
            bool prime=true;
            for (int j=2; j*j<=i; j++)
            {
                if (i % j == 0) 
                {
                    prime=false;
                    break;    
                }
            }   
            if(prime) cout << i << " ";
        }
        return 0;
    }
    

    3.

    #include <vector>
    int main()
    {
        std::vector<int> primes;
        primes.push_back(2);
        for(int i=3; i < 100; i++)
        {
            bool prime=true;
            for(int j=0;j<primes.size() && primes[j]*primes[j] <= i;j++)
            {
                if(i % primes[j] == 0)
                {
                    prime=false;
                    break;
                }
            }
            if(prime) 
            {
                primes.push_back(i);
                cout << i << " ";
            }
        }
    
        return 0;
    }
    

    Edit: In the third example, we keep track of all of our previously calculated primes. If a number is divisible by a non-prime number, there is also some prime <= that divisor which it is also divisble by. This reduces computation by a factor of primes_in_range/total_range.

    0 讨论(0)
  • 2020-11-28 06:01

    The book seems to be "C++ for Engineers and Scientists" written by Gary Bronson (googled it).
    Is this a possible answer? IMHO it's surprising.

    I had to read the question (from the book) a few times. My interpretation:
    For each number N: 2 <= N < 100 check whether it's prime.
    How? For each divisor D: 2 <= D < sqrt(N) ,
    if D divides N, N is not prime, if D > sqrt(N), N is prime.

    Give it a try:

    N = 2, sqrt(2) ≈ 1.41, D = 2, 2 < 1.41 ?  no 2 > 1.41 ? yes 2 is prime.  
    N = 3, sqrt(3) ≈ 1.73, D = 2, 2 < 1.73 ?  no 2 > 1.73 ? yes 3 is prime.  
    N = 4, sqrt(4) = 2.00, D = 2, 2 < 2.00 ?  no 2 > 2.00 ?  no 4 is not prime.  
    N = 5, sqrt(5) ≈ 2.24, D = 2, 2 < 2.24 ? yes 5 % 2 > 0? yes  
                           D = 3, 3 < 2.24 ?  no 3 > 2.24 ? yes 5 is prime.    
    N = 6, sqrt(6) ≈ 2.45, D = 2, 2 < 2.45 ? yes 6 % 2 = 0  2 > 2.45 ? no 6 is not prime.
    

    As far as I can see, that's how the primes should be found,
    not with a sieve (much, much faster),
    but with: the answer is in the question! Surprising?

    Speed? primes < 400,000 : less than 10 seconds (on my watch, a rolex, I bought it on the market, the seller said it was a real one, a real one for the price of two baguettes, with 12 real diamonds as well).
    Let's count the primes (I'm not going to show code ;) : 664579 primes < 10,000,000 : 5 seconds.

    #include "stdafx.h"
    #include <math.h>
    #include <iostream>
    using namespace std;
    int main()
    {
        double rt;
        for (int d = 2, n = 2; n < 100; d = 2, n++)
        {
            for (rt = sqrt(n); d < rt; d++)
                if (n % d == 0) break;
            if (d > rt) cout << n << " ";
        }
        getchar();  // 25 primes :-)
    }
    

    Deleted an earlier answer with (like other answers) a prime-sieve.
    Hopefully I get my next "Necromancer" badge soon.

    I asked the author: In your book: "C++ for E&S" is an exercise about prime numbers,[xrcs]...[/xrcs]. Seven years ago it was asked at: SO/q/5200879
    A few days ago I gave an answer: SO/a/49199435
    Do you think it is a reasonable solution, or perhaps the solution.

    He replied: Peter, I never really have a specific solution in mind when I am making up the exercises,
    so I can’t say I had your exact solution in mind. The joy of C++ is that one can come up with really creative solutions and great code, as, on first glance, it looks like you have done.
    Thanks for sending it!
    Dr. Bronson

    I went to https://youtu.be/1175axY2Vvw

    PS. A sieve: https://pastebin.com/JMdTxbeJ

    0 讨论(0)
  • 2020-11-28 06:02

    To find whether no. is prime or not C++:

    #include<iostream>
    #include<cmath>
    
    using namespace std;
    int main(){
    
    int n, counter=0;
    
    cout <<"Enter a number to check whether it is prime or not \n";
    cin>>n;
    
      for(int i=2; i<=n-1;i++) {
        if (n%i==0) {
          cout<<n<<" is NOT a prime number \n";
          break;
        }
        counter++;
                    }
        //cout<<"Value n is "<<n<<endl;
        //cout << "number of times counter run is "<<counter << endl;
        if (counter == n-2)
          cout << n<< " is prime \n";
       return 0;
    }
    
    0 讨论(0)
提交回复
热议问题