第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

在Java中測(cè)試primality的最快方法是什么?

在Java中測(cè)試primality的最快方法是什么?

嚕嚕噠 2019-09-20 16:57:50
我試圖找到檢查給定數(shù)字是否為素?cái)?shù)的最快方法(在Java中)。以下是我提出的幾種素性測(cè)試方法。有沒(méi)有比第二個(gè)實(shí)現(xiàn)更好的方法(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貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超18個(gè)贊

你邁出了消除2的所有倍數(shù)的第一步。


但是,你為什么要止步呢?你可以消除所有3的倍數(shù),除了3,所有5的倍數(shù)除了5,等等。


當(dāng)你按照這個(gè)推理得出結(jié)論時(shí),你會(huì)得到Eratosthenes的篩子。


查看完整回答
反對(duì) 回復(fù) 2019-09-20
  • 3 回答
  • 0 關(guān)注
  • 849 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)