Monday, April 1, 2013

Prime numbers (by value)

A function that returns 1 if a number is prime and 0 otherwise.

/* Function finding prime numbers (no pointers) */
#include <stdio.h> #include <math.h> /* function returns true if n is even. */ /* it returns false if n is odd */ int even (int n) { return (n%2==0); } /* function returns true if n is prime */ int prime (int n) { int divisor, i; /* looking for a divisor. if found, it is not a prime number */ divisor = 0; /* eliminating even numbers except 2 */ if (even (n)) { if (n == 2) divisor = 0; else divisor = 2; } else { if (n == 1) divisor = 0; /* 1 is a prime number */ else /* trying to divide number by 3,5,7,... */ /* to find a divisor until we reach n-1 */ for (i = 3; i < n; i = i + 2) { if (n % i == 0) divisor = i; } } /* if there is a divisor (not zero) then NOT prime */ return (!divisor); } int main (void) { int x; printf ("Enter a positive integer number: "); scanf ("%d", &x); /* testing for prime and printing the report */ if (prime (x)) printf ("%d is a prime number.\n", x); else printf ("%d is not a prime number.\n", x); return (0); }
Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
Enter a positive integer number: 59
59 is a prime number.

1 comment: