#1
  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. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,387
    Rep Power
    1871
    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
    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
  4. #3
  5. 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

IMN logo majestic logo threadwatch logo seochat tools logo