How to create the most compact mapping n → isprime(n) up to a limit N?

后端 未结 30 3227
遇见更好的自我
遇见更好的自我 2020-11-22 02:11

Naturally, for bool isprime(number) there would be a data structure I could query.
I define the best algorithm, to be the algorithm that pr

30条回答
  •  没有蜡笔的小新
    2020-11-22 02:54

    Similar idea to the AKS algorithm which has been mentioned

    public static boolean isPrime(int n) {
    
        if(n == 2 || n == 3) return true;
        if((n & 1 ) == 0 || n % 3 == 0) return false;
        int limit = (int)Math.sqrt(n) + 1;
        for(int i = 5, w = 2; i <= limit; i += w, w = 6 - w) {
            if(n % i == 0) return false;
            numChecks++;
        }
        return true;
    }
    

提交回复
热议问题