我正在尝试找到检查给定数字是否为质数的最快方法(使用Java)。以下是我想出的几种质数测试方法。除了第二种实现(isPrime2),还有更好的方法吗?
public class Prime {
public static boolean isPrime1(int n) {
if (n <= 1) {
return false;
}
if (n == 2) {
return true;
}
for (int i = 2; i <= Math.sqrt(n) + 1; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static boolean isPrime2(int n) {
if (n <= 1) {
return false;
}
if (n == 2) {
return true;
}
if (n % 2 == 0) {
return false;
}
for (int i = 3; i <= Math.sqrt(n) + 1; i = i + 2) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
public class PrimeTest {
public PrimeTest() {
}
@Test
public void testIsPrime() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
Prime prime = new Prime();
TreeMap<Long, String> methodMap = new TreeMap<Long, String>();
for (Method method : Prime.class.getDeclaredMethods()) {
long startTime = System.currentTimeMillis();
int primeCount = 0;
for (int i = 0; i < 1000000; i++) {
if ((Boolean) method.invoke(prime, i)) {
primeCount++;
}
}
long endTime = System.currentTimeMillis();
Assert.assertEquals(method.getName() + " failed ", 78498, primeCount);
methodMap.put(endTime - startTime, method.getName());
}
for (Entry<Long, String> entry : methodMap.entrySet()) {
System.out.println(entry.getValue() + " " + entry.getKey() + " Milli seconds ");
}
}
}
a/4
改为(a>>2)
以节省时间...现代编译器已经了解这一点,并自动执行这样的替换,因此更好的程序员可以写出他们想要的a/4
。”这只是一个思考的问题。 - SimonTa/4
与a>>2
不同,因为负数会向上舍入而不是向下。除非编译器能够证明a>=0
,否则它必须生成一个相当复杂的表达式来避免除法(仍然是一种改进,但大约需要3个周期而不是单个指令)。 - maaartinus