#include <stdio.h>
#define FALSE 0
#define TRUE 1 /* we define 0 and 1 as false and true so we can use them later, so it's more obvious what the code means.*/
int main()
{
int myNumber; /* the number the user enters is stored in this*/
int isPrime = TRUE; /* we will set this to true, and if we find it not to be prime, we change it to false.*/
/* if after we've checked all divisors it is still true, we know it to be prime*/
int i = 0; /*this variable is used as a counter*/
printf("Please enter a positive integer: "); /* ask the user to enter a number to test the primality of */
scanf("%d", &myNumber);
if(myNumber == 1) /* first we deal with special cases and tell the user off if he/she enters a silly number*/
{
printf("1 is not prime.");
return 0; /* return 0 ends the program */
}
else if(myNumber <= 0)
{
printf("Error. Please enter a positive number.");
return 0;
}
for(i=2;i<myNumber;i++) /*in this for-loop we test to see whether every number below our number is a factor of it */
{ /*if any number is a factor, we deduce we don't have a prime*/
/*i successively takes values from 2 to myNumber-1.*/
if(myNumber%i == 0) /*here, % calculates the remainder. so if our remainder is zero, we know we have a factor*/
{
printf("%d is divisible by %d so it is not prime.", myNumber, i);
isPrime = FALSE;
break; /*we've realized we don't have a prime, so this breaks the for-loop as we can stop searching for factors.*/
}
}
if(isPrime) /*if-statements treat all non-zero values as true. and we defined TRUE as 1.*/
printf("%d is prime!", myNumber);
return 0; /* exit the program */
}