Created
October 29, 2012 01:48
-
-
Save anonymous/3970941 to your computer and use it in GitHub Desktop.
tests for prime
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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