# Thread: Is it prime number or not

1. ## Is it prime number or not

Prompt user for an integer

IF n is less than 2
Set prime to 0 ( 0 means false, i.e. n is not prime )
ELSE
Set prime to 1 ( 1 means true, i.e. assume n is prime )
FOR values of i from 2 to n - 1 ( i represents all numbers smaller than n )
IF n divided by i gives no remainder
Set prime to 0 ( 0 means false, i.e. n is not prime )
BREAK ( jump out from the loop )
END IF
END FOR
END IF

IF prime = 1
Print message for prime number
ELSE
Print message for not prime number
END IF

I follow this algorithm but it's not working ...
Code:
```#include <stdio.h>

int main ()

{

int n, i, prime;

printf("Enter a number : ");
scanf("%d", &n);

if (n<2)
{
prime = 0;
}
else
{
prime = 1;
for (i=2;i<n;n--)
{
if (n%i==0)
{
prime = 0;
break;
}
}
}

if (prime==1)
{
printf("Prime number\n", n);
}
else
{
printf("Not a prime number\n", n);
}

return 0;

}```

2. Your for loop is wrong. You want to increment i and not decrement n. n should not change at all.

3. I see ... i changed it to i++; and it's working now
but what is the meaning of FOR values of i from 2 to n - 1 ( i represents all numbers smaller than n ), i though that n-1 = n--?

4. You are modifying n, the number being checked for primeness, instead of incremening your counter ie "i".

Code:
```for( i = 2; i < n; ++i){
if( !( n % i ) ){
prime = 0;
break;
{
}```

5. Originally Posted by CruelSoulz
I see ... i changed it to i++; and it's working now
but what is the meaning of FOR values of i from 2 to n - 1 ( i represents all numbers smaller than n ), i though that n-1 = n--?
i is your loop variable, it is what changes each time through the loop (you can think of it as i goes from 2 to n-1, from being a keyword from the pseudo code)
2 is the starting value for i
n is the number you wish to check if it is prime
n - 1 is one less than that number, i.e. if you wish to check whether 13 is prime, n is 13 and n - 1 is 12

n-- on the other hand mean "use the current value of n, then decrement it". For example, if n was 13, and you did x = n--; you would set x to the value of n (i.e. x = 13), then subtract one from n (i.e. n = n - 1)

Hope that's clear.

6. Originally Posted by CruelSoulz
I see ... i changed it to i++; and it's working now
but what is the meaning of FOR values of i from 2 to n - 1 ( i represents all numbers smaller than n ), i though that n-1 = n--?
n is the number you are checking to see if it's prime. Throughout the test of lesser numbers, you want to change the current number being tested as a factor of n, but you do NOT want to change n, ever.

BTW, you can stop testing numbers as a factor, when i > square root of n. Little math speed up for you.

7. Oh ... i get it , thanks