简体   繁体   中英

Understanding C example from a book?

I am learning from Programming in C by Stephen Kochan. Program 7.4 Revising the Program to Generate Prime Numbers, Version 2:

#include <stdio.h>
#include <stdbool.h>

// Modified program to generate prime numbers
int main (void)
{
    int p, i, primes[50], primeIndex = 2;
    bool isPrime;
    primes[0] = 2;
    primes[1] = 3;

    for ( p = 5; p <= 50; p = p + 2 ) {
        isPrime = true;

        for ( i = 1; isPrime && p / primes[i] >= primes[i]; ++i )
            if ( p % primes[i] == 0 )
            isPrime = false;
            if ( isPrime == true ) {
                primes[primeIndex] = p;
                ++primeIndex;
            }
        }
        for ( i = 0; i < primeIndex; ++i )
            printf ("%i ", primes[i]);

    printf ("\n");
    return 0;
}

The problem is I failed to understand how its works.

The expression

  p / primes[i] >= primes[i] 

Is used in the innermost for loop as a test to ensure that the value of p does not exceed the square root of primes[i] .This test comes directly from the discussions in the previous paragraph. (You might want to think about the math a bit.)

After that book show me that another line:

If it is, then isPrime is set false. The for loop continues execution so long as the value of isPrime is true and the value of primes[i] does not exceed the square root of p .

please explain that line

Prime number is only divided by 1 and itself.
So, maximum number that can be divisible is square root of it.

The below are same equation if p is a positive integer.

1) primes[i] <= square root of (p)  
2) primes[i] * primes[i] <= p
3) p >= primes[i] * primes[i]
4) p / primes[i] >= primes[i]

suppose the number p = 99 then the loop will check sqrt(99) = 9 that is upto 9 prime if there is no isPrime check in the loop. that is :

for ( i = 1;  p / primes[i] >= primes[i]; ++i )
        if ( p % primes[i] == 0 )
          isPrime = false;

then it will go upto 9 prime check even though 99 is divisible by 3. But 99 is divisible by 3. So do we need to test it further more?? Nope so we can stop here and thats why we set a flag variable to test if it is already divisible by any prime in range that 9 prime.

So if we add isPrime in loop that is:

for ( i = 1; isPrime && p / primes[i] >= primes[i]; ++i )
            if ( p % primes[i] == 0 )
            isPrime = false;

then after the second iteration it will stop as isPrime then set false and this is much more efficient.

I hope You understand.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM