IHYPRESS PROGRAMMING
Tutorials and C programs with code and output for beginners
c programming
HOME | ASP | C | CSS | GNUPLOT | HTML | JAVASCRIPT | PERL | PHP | PYTHON | RUBY | SVG
CSimple Functions : Prime Number Determination
<05.06>
/* 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); }
Hergestellt in Deutschland / Made in Germany
Enter a positive integer number: 59 59 is a prime number.
COPYRIGHT © 2015-2024 IHY PRESS Frankfurt am Main 60329 Deutschland