Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
August 24th, 2013, 01:22 AM
 diego13
Registered User

Join Date: Aug 2013
Posts: 2
Time spent in forums: 47 m 58 sec
Reputation 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.

#2
August 24th, 2013, 02:41 AM
 salem
Contributed User

Join Date: Jun 2005
Posts: 4,252
Time spent in forums: 2 Months 4 Weeks 1 Day 12 h 25 m 37 sec
Reputation Power: 1809
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.
eramit2010 agrees!
__________________
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper

#3
August 25th, 2013, 01:01 AM
 diego13
Registered User

Join Date: Aug 2013
Posts: 2
Time spent in forums: 47 m 58 sec
Reputation Power: 0
Thanks (SOLVED)

Quote:
 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

 Viewing: Dev Shed Forums > Programming Languages > C Programming > For loop for test prime numbers