### Thread: For loop for test prime numbers

1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Aug 2013
Posts
2
Rep Power
0

#### For loop for test prime numbers

Hi, In the following code, a test for determining the primality of a number is made:
Code:
```#include <stdio.h>
#include <math.h>

int main()
{
unsigned int n, FLAG_PRIME;
unsigned int n_square;
unsigned int x;

FLAG_PRIME = 1;

printf("\nUntil which limit?: ");
scanf("%d", &n);
n_square = (unsigned int)sqrt((double)n);

for(x = 2; x == n_square; ++x)
{
if (n % x == 0)
FLAG_PRIME = 0;
}

if (FLAG_PRIME == 1)
printf("%d prime\n", n);
else
printf("%d not prime\n", n);

return 0;
}```
However, in the line
Code:
`for(x = 2; x == n_square; ++x)`
I don't know the value of x for numbers in which the square root of n (n_square) is shorter than x ie sqrt(2) = 1.414. It's a Little puzzling since it works but I would like to know the behavior of for loops in this particular cases.

Thanks in advanced
2. If you want to know how it works (or more accurately, doesn't work), then do this.
Code:
```	for(x = 2; x == n_square; ++x)
{
printf("Checking if %d is a divisor of %d\n", x, n );
if (n % x == 0)
FLAG_PRIME = 0;
}```
FYI, the for loop only runs while the test expression returns true.

#### Comments on this post

• eramit2010 agrees
3. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Aug 2013
Posts
2
Rep Power
0

#### Thanks (SOLVED)

Originally Posted by salem
If you want to know how it works (or more accurately, doesn't work), then do this.
Code:
```	for(x = 2; x == n_square; ++x)
{
printf("Checking if %d is a divisor of %d\n", x, n );
if (n % x == 0)
FLAG_PRIME = 0;
}```
FYI, the for loop only runs while the test expression returns true.
Since for doesn't run in those cases and Flag 1 is the default, it appeared that worked. Your reply was very helpful and is greatly appreciated