Search code examples
cfor-loopprimes

I don't understand the for loop with this prime number checker


I don't understand how this checks for prime numbers:

int n,f;
  
printf("");
scanf("%d",&n);

int p=0;

for (f=1;f<=n;f++)
{
   if (n%f==0)
   {
     p=p+1;
   }
}

if (p==2)
{
   printf("prime");
}
else
{
   printf("not prime");
}

What is p=0, p=p+1, and p==2? Where did these assignments/comparisons come from?


Solution

  • The code is basically checking all the factors of the input number, including 1 and the number itself. Primes are by definition any number that has no other factor other than itself and 1, so if the 'p' factor term equals 2 it means the number is prime because the increment has happened at 1 and the number only.