Hi folks,
I was going through a book I have about C trying to learn about arrays, and one of the first few examples of what could been done with an array was showing how to use an array to generate a list of prime numbers. I've been staring at this program for about an hour trying to understand how it works (it does), but the workings of one for loop within the program absolutely confuses me. I was hoping y'all could help me understand. This is the program: ( I commented out the for loop that I don't understand ).
Code:
#include <stdio.h>
#include <stdbool.h>
int main () {
int p, i, primes[50], primeIndex = 2;
bool isPrime;
primes[0] = 2;
primes[1] = 3;
for ( p = 5; p <= 50; 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 loop condition in particular is the part that I don't understand...
Code:
isPrime && p / primes[i] >= primes[i]
So that is saying in order for this loop to go on, really two conditions must be met since there's that && operator. isPrime must be true (I think that's what it means by just having "isPrime" and not setting it equal to anything) and p / primes[i] must be greater than or equal to primes[i].
So at the beginning of the loop, since i = 1, p = 5 (as per surrounding loop), and prime[i] = 3 ( as per the variable assignment at the beginning of the program ), the loop condition would be "isPrime && 5 / 3 >= 3"
"5 / 3 >= 3" WTF??? The loop should stop right there! 1.666666667 is NOT greater than or equal to 3!
What am I missing here? Obviously I'm misinterpreting or not seeing something, but I can't figure out what that is... Any ideas?