There is an algorithm to check is a number prime/semiprime/composite.
Pseudo code:
Input a number N and if N – 1 and N + 1 is not divisible by 6 then the number N is Not Prime. else it is prime or semi-prime
If n-1 or n+1 is divisible by 6 then iterate in the range(sqrt(N) + 1, N) and find a pair (p, q) such that p*q = N by below formula:
p = i - sqrt(i*i - N)
q = n/p
where i = index in range(sqrt(N) + 1, N)
If p*q = N then the number N is semi prime, else it is prime
But it fails for some semi-prime number. For 6 it gives composite instead of semi-prime. For 10 it gives composite instead of semi-prime. But for 7894561 it gives semi-prime as should.
Is there optimal algorithm to deduce is a number prime/semi-prime/composite? Perhaps I misuse the algorithm and don't understand it's limitations? It is explained that number should be greater than 300. But why 300? Does it always work properly for numbers greater than 300? Please advise.
Below is the C++ implementation of the approach:
#include<bits/stdc++.h>
using namespace std ;
void prime(long n)
{
int flag = 0;
// checking divisibilty by 6
if ((n + 1) % 6 != 0 && (n - 1) % 6 != 0)
{
cout << ("Composite") << endl;
}
else
{
// breakout if number is perfect square
double s = sqrt(n);
if ((s * s) == n)
{
cout<<("Semi-Prime")<<endl;
}
else
{
long f = (long)s;
long l = (long)((f * f));
// Iterating over to get the
// closest average value
for (long i = f + 1; i < l; i++)
{
// 1st Factor
long p = i - (long)(sqrt((i * i) - (n)));
// 2nd Factor
long q = n / p;
// To avoid Convergence
if (p < 2 || q < 2)
{
break;
}
// checking semi-prime condition
if ((p * q) == n)
{
flag = 1;
break;
}
// If convergence found
// then number is semi-prime
else
{
// convergence not found
// then number is prime
flag = 2;
}
}
if (flag == 1)
{
cout<<("Semi-Prime")<<endl;
}
else if (flag == 2)
{
cout<<("Prime")<<endl;
}
}
}
}
// Driver code
int main()
{
prime(8179);
prime(7894561);
prime(90000000);
prime(841);
prime(22553);
prime(1187);
}
I used the article.