IHYPRESS.NET > C PROGRAMMING
HOME | CLASSIC ASP | C | HTML/CSS | JAVASCRIPT | PERL | PHP | PYTHON | RUBY
C > 05. Functions I [PROGRAM #06]
CODERESULT
<
/* 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 function | helper functions | user-defined structures comments
Enter a positive integer number: 59
59 is a prime number.
>
COPYRIGHT © 2021 IHYPRESS.NET. A DIVISION OF IHY PRESS, KIRKLAND, WA 98083 USA. ALL RIGHTS RESERVED.