Solved

# Prime number - Conditional expression in For loop

Posted on 2011-09-19

Hi,

This program is created to find the prime numbers between 2 and 20.

inside the second for loop, the conditional statement is i <= num/2.

why do we use this as our conditional statement?

int factor;

bool isPrime;

for (int num = 2; num < 20; num++)

{

isPrime = true;

factor = 0;

Console.WriteLine("num " + num);

// see if num is evenly divisible.

for (int i = 2; i <= num/2; i++)

{

Console.WriteLine("i: " + i + " num/2: " + num/2 + " num%2 " + num%i);

if ((num % i) == 0)

{

// num is evenly divisible. Thus, it is not prime.

isPrime = false;

factor = i;

}

Console.WriteLine("factor: " + factor);

}

if (isPrime)

Console.WriteLine(num + " is prime.");

else

Console.WriteLine("Largest factor of " + num + " is " + factor);