so I'm trying to create a function, which will return either 1 or 0, depending whether the given number is or isn't a prime number.
NOTE: I know for certain that the given number is Natural. Greater than 1
My original function:
int Prime(int a) {
int i;
for (i = 2; i*i <= a; i++)
{
if ((a % i) == 0)
return 0;
};
return 1;
}
works just fine, but is somehow... slow. I'm looking for a more efficient algorithm without using an array . My second try:
int Prime(int a) {
int i;
if (a == 2)
return 1;
if ((a % 2) == 0)
return 0;
for (i = 3; i*i <= a; i = i + 3)
{
if ((a % i) == 0)
return 0;
};
return 1;
}
ended badly. There is some number (which I can't really imagine), less than MAX_INT
, that causes this particular algorithm to work extremely slowly. So, I have 2 questions:
Is something wrong with my upgraded algorithm?
Is there any way to do this task more efficiently?