Skip to content

Instantly share code, notes, and snippets.

@cyberhck
Created December 25, 2014 09:41
Show Gist options
  • Save cyberhck/6515dadd2f23adc65cf1 to your computer and use it in GitHub Desktop.
Save cyberhck/6515dadd2f23adc65cf1 to your computer and use it in GitHub Desktop.
A better than our lab isPrime function.
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int main(){
int n;
printf("Enter a number\n");
scanf("%d",&n);
if(isPrime(n)){
printf("Is prime number\n");
}else{
printf("Is not a prime number\n");
}
return 0;
}
int isPrime(int a){
int i;
if(a==2 | a==3){
return 1;
//obviously if the number is 2 or 3, it's prime
}
if(a%2==0 | a%3==0){
return 0;
//if it is divisible by 2 or 3 they aren't prime.
}
else{
for(i=5;i<=sqrt(a);i=i+2){
//2 and 3 are already checked, 4 is not prime so we don't need to check, we can start from 5, then we don't need to check with any of even numbers, so skip a number each time.
if(!isPrime(i)){
//if I is not prime, that means it can be broken down to prime factors, and that means those factors are less than i, which already checked dividing, so we can skip those non prime numbers.
continue;
}else{
if(a%i==0){
return 0;
//if the counter is prime and it divides the number without a 0 reminder, that means number is not prime
}
}
}
//at this point, every possible check are done and the conclusion is, the number is prime.
return 1;
}
}
@cyberhck
Copy link
Author

While compiling on GNU/Linux OS, (I don't care about other operating systems) please use -lm flag for math.h file, only including it is not enough, or you'll get an error saying "undefined reference to sqrt" so while compilation use:
cc isPrime.c -o isPrime -lm
./isPrime

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment