为了账号安全,请及时绑定邮箱和手机立即绑定

在Java中测试primality的最快方法是什么?

在Java中测试primality的最快方法是什么?

噜噜哒 2019-09-20 16:57:50
我试图找到检查给定数字是否为素数的最快方法(在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 ");        }    }}
查看完整描述

3 回答

?
慕容森

TA贡献1853条经验 获得超18个赞

你迈出了消除2的所有倍数的第一步。


但是,你为什么要止步呢?你可以消除所有3的倍数,除了3,所有5的倍数除了5,等等。


当你按照这个推理得出结论时,你会得到Eratosthenes的筛子。


查看完整回答
反对 回复 2019-09-20
  • 3 回答
  • 0 关注
  • 761 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信