Printing prime numbers from 1 through 100

前端 未结 22 2529
无人共我
无人共我 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条回答
  •  猫巷女王i
    2020-11-28 05:52

    Finding primes up to a 100 is especially nice and easy:

        printf("2 3 ");                        // first two primes are 2 and 3
        int m5 = 25, m7 = 49, i = 5, d = 4;
        for( ; i < 25; i += (d=6-d) )
        {
            printf("%d ", i);                  // all 6-coprimes below 5*5 are prime
        }
        for( ; i < 49; i += (d=6-d) )
        {
            if( i != m5) printf("%d ", i);
            if( m5 <= i ) m5 += 10;            // no multiples of 5 below 7*7 allowed!
        }
        for( ; i < 100; i += (d=6-d) )         // from 49 to 100,
        {
            if( i != m5 && i != m7) printf("%d ", i);
            if( m5 <= i ) m5 += 10;            //   sieve by multiples of 5,
            if( m7 <= i ) m7 += 14;            //                       and 7, too
        }
    

    The square root of 100 is 10, and so this rendition of the sieve of Eratosthenes with the 2-3 wheel uses the multiples of just the primes above 3 that are not greater than 10 -- viz. 5 and 7 alone! -- to sieve the 6-coprimes below 100 in an incremental fashion.

提交回复
热议问题