如题,分享几个自己精心收集并改进的素数算法:
public class PrimeTool
{
/**
* 判断是否为素数
*
* @param number
* @return
*/
public static boolean isPrime(int number)
{
if (number < 2)
return false;
if (number == 2)
return true;
if (number % 2 == 0)
return false;
for (int i = 3, j = (int) Math.sqrt(number); i <= j; i += 2)
{
if (number % i == 0)
{
return false;
}
}
return true;
}
/**
* 获取不大于number的所有素数
*
* @param number
* @return int数组
*/
public static int[] makePrimes3(int number)
{
if (number < 2)
return null;
if (number == 2)
return new int[] { 2 };
if (number == 3)
return new int[] { 2, 3 };
int[] primes = new int[number / 2 + 1];
primes[0] = 2;
primes[1] = 3;
primes[2] = 5;
int cnt = 3;
for (int i = 7; i <= number; ++i)
{
if (i % 2 == 0 || i % 3 == 0 || i % 5 == 0)
{
continue;
}
if (isPrime(i))
{
primes[cnt++] = i;
}
}
int[] array = new int[cnt];
System.arraycopy(primes, 0, array, 0, cnt);
return array;
}
/**
* 构造素数序列primes[]
*
* 原理:线行筛选
*
* @param primes
* @param number
* @param flag
* true则返回所有不大于number的素数,false则返回前number个素数
* @return primes数组实际长度
*/
private static int makePrimesnumberber(int[] primes, int number,
boolean flag)
{
if (number < 2)
return 0;
primes[0] = 2;
if (number == 2)
return 1;
primes[1] = 3;
boolean isPrimes;
int i, j, cnt;
for (i = 5, cnt = 2; (flag ? i : cnt) < number; i += 2) //基本类型无法引用,不知道有没有更好地实现
{
isPrimes = true;
for (j = 1; primes[j] * primes[j] <= i; ++j)
{
if (i % primes[j] == 0)
{
isPrimes = false;
break;
}
}
if (isPrimes)
primes[cnt++] = i;
}
return cnt;
}
/**
* 获取不大于number的所有素数
*
* @param number
* @return int数组
*/
public static int[] makePrimes2(int number)
{
int[] primes = new int[number / 2 + 1];
int total = makePrimesnumberber(primes, number, true);
int[] array = new int[total];
System.arraycopy(primes, 0, array, 0, total);
return array;
}
/**