Skip to content

Instantly share code, notes, and snippets.

Created October 29, 2012 01:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/3970941 to your computer and use it in GitHub Desktop.
Save anonymous/3970941 to your computer and use it in GitHub Desktop.
tests for prime
/*
* file: prime.c
* Asks user to input an integer number, checks if
* given number is prime or not and prints result of check.
*
*/
#include <stdio.h>
/* checks if argument is a prime number
* returns 1 if it is, return 0 otherwise */
int prime(int x)
{
/* handle special cases */
if(x<=2)
return 1;
int i;
/* largest number to take into account is sqrt x */
for(i=2; i*i<=x; i++)
{
/* if there is a number that divides x */
if((x%i) == 0)
return 0;
}
return 1;
}
int main()
{
int x;
/* ask user for input */
printf("Please enter a number: ");
scanf("%i", &x);
/* check if users number is a prime number */
if(prime(x))
printf("%i is a prime number\n", x);
/* check if users number is not a prime number */
if(!prime(x))
printf("%i is not a prime number\n", x);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment