Printing prime numbers from 1 through 100

前端 未结 22 2477
无人共我
无人共我 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: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 
    #include 
    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

提交回复
热议问题