Morning,
I bought the book, "Learn C on the Mac"
So far have been enjoying it but have become stumped at one section.
I was hoping someone could help.
Its to do with the exercise on prime numbers in chap 6.
Regarding the loop to determine whether a number is prime - to me it sounds like the program is able to make out what a prime number is yet we still need to prove a number is a prime.
am i wrong in thinking this.
Code:
int main (int argc, const char * argv[]) {
bool isPrime;
int startingPoint, candidate, last, i;
startingPoint = 24;
if ( startingPoint < 2 ) {
candidate = 2;
}
else if ( startingPoint == 2 ) {
candidate = 3;
}
else {
candidate = startingPoint;
if (candidate % 2 == 0) /* Test only odd numbers */
candidate--;
do {
isPrime = true; /* Assume glorious success */
candidate += 2; /* Bump to the next number to test */
last = sqrt( candidate ); /* We'll check to see if candidate */
/* has any factors, from 3 to last */
/* Loop through odd numbers only */
for ( i = 3; (i <= last) && isPrime; i += 2 ) {
// Here it looks as
//though the program can deduce whether a number is prime
//yet we still need to tell it what a prime number is.
// - the "&& isPrime" sounds as though it can deduce
// whether a number is prime
if ( (candidate % i) == 0 )
isPrime = false;
}
} while ( ! isPrime );
}
printf( "The next prime after %d is %d. Happy?\n",
startingPoint, candidate );
return 0;
}
Thanks,
/84.