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

后端 未结 30 3213
遇见更好的自我
遇见更好的自我 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:52

    bool isPrime(int n) {
    if(n <= 3)
        return (n > 1)==0? false: true;
    else if(n%2 == 0 || n%3 == 0)
        return false;
    
    int i = 5;
    
    while(i * i <= n){
        if(n%i == 0 || (n%(i+2) == 0))
            return false;
        i = i + 6;
    }
    
    return true;
    }
    

    for any number, the minimum iterations to check if the number is prime or not can be from 2 to square root of the number. To reduce the iterations, even more, we can check if the number is divisible by 2 or 3 as maximum numbers can be eliminated by checking if the number is divisible by 2 or 3. Further any prime number greater than 3 can be expressed as 6k+1 or 6k-1. So the iteration can go from 6k+1 to the square root of the number.

提交回复
热议问题