Introduction to Computer Science - Fall 2004

/* Author Yana
This program checks whether input number is prime or not. Version 2.
Input: A non-negative integer n.
Output: A message whether n is prime or not.
Algorithm:
1. Read the input number.
2. Special cases: n <= 1 is not prime. n == 2 is prime.
3. n > 2: Check for divisors up to int( sqrt(n) + 0.5 ).
Stop checking when a divisor is found.
4. n is prime if no divisor was found.
Remark: The variable 'max_divisor' is rounded to the nearest integer,
because sqrt(n) returns a double and on some computers may return for example sqrt(49) = 6.9999.     */


#include<stdio.h>
#include<math.h>
int main(){

    int n;             /* Input number tested. */
    int divisor = 2;       /* First possible divisor tested. */
    int max_divisor;       /* Largest divisor tested. */
    int prime = 1;       /* 1 (means true) if n prime, 0 (means false) otherwise. */

    /* Read input */
    printf("Please enter a non-negative number ");
    scanf("%d", &n);

    if (n <= 1)       /* Check for n<=1. */
      prime = 0;       /* n = 1 or n = 0 not prime numbers */
    else if (n>2){

      max_divisor = (int)( sqrt( n ) + 0.5 );

      /* check all divisors up to max_divisor. Stop when a divisor is found. */
      while ( ( divisor <= max_divisor ) && ( prime ) ){
        if (n % divisor == 0)
          prime = 0;
        divisor ++;
      }
    }

    /* Print output */
    if ( prime )
      printf("The number %d is prime\n", n);
    else
      printf( "The number %d is not prime\n", n);

    return 0;
}