
Patrick B. answered 03/21/21
Math and computer tutor/teacher
The algorithm is of polynomial order...
O (n^k) where k is the # of primes...
Not very efficient...
It is much more efficient just to look for divisors between 2 and sqrt(x)
-------------------------------------------------------------------------------------------
import java.math.*;
class PrimeNumber
{
// returns the first integer divisor of x that is less than sqrt(x), or -1 if prime
public long IsPrime( long x)
{
long iReturn = -1;
if (x==2) { iReturn=-1; }
else if (x==3) { iReturn=-1; }
else if (x==4) { iReturn=2; }
else if (x==5) { iReturn=-1; }
else if (x==6) { iReturn=2; }
else
{
long iStop = (long)(Math.ceil(Math.sqrt(x))+1);
for (long iLoop=2; iLoop< iStop; iLoop++)
{
if ((x % iLoop)==0)
{
iReturn = iLoop;
break;
}
}
}
return(iReturn);
}
public static void main(String args[])
{
int N=50;
if (args.length>0)
{
N = Integer.parseInt(args[0]);
}
PrimeNumber myPrime = new PrimeNumber();
for (int iLoop=2; iLoop<N; iLoop++)
{
if (myPrime.IsPrime(iLoop) == -1)
{
System.out.println(iLoop);
}
}
}
}