Click here to Skip to main content
15,912,977 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Here is my doubt , a friend of mine pass me this code, that the function is finding if the provided number is prime or not .
The problem is that I do not understand why the code works,get it? I can not understand the logic behind the algorithm.
Here is the code :http://www.mediafire.com/view/?c2o477ach484kbd
Thanks for any help .

C++
int main(void)
{
int n, c = 2;

printf("enter the value:");
scanf("%d",&n);

for ( c = 2 ; c <= n - 1 ; c++ )
{
if ( n%c == 0 )
{
printf("not a prime number");
break;
}
}
if ( c == n )
printf("prime number");

system("PAUSE");	
return 0;
}
Posted

Well, that's not the most efficient way, but yes, such code is correct: if a number is prime then then its integer division by a smaller number produces a (non-zero) reminder. Your friend's code exploits such property.
 
Share this answer
 
You could read this, it might be helpful:
Finding prime numbers[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900