Are You A Prime Number

后端 未结 11 2172
甜味超标
甜味超标 2021-02-10 07:39

I\'ve been interested in the problem of finding a better prime number recognizer for years. I realize this is a huge area of academic research and study - my interest in this i

11条回答
  •  有刺的猬
    2021-02-10 08:08

    Here's my algorithm, Complexity remains O(n^0.5) but i managed to remove some expensive operations in the code...

    The algorithm's slowest part is the modulus operation, i've managed to eliminate sqrt or doing i * i <= n

    This way i save precious cycles...its based on the fact that sum of odd numbers is always a perfect square.

    Since we are iterating over odd numbers anyway, why not exploit it? :)

    int isPrime(int n)
    {
        int squares = 1;
        int odd = 3;
    
        if( ((n & 1) == 0) || (n < 9)) return (n == 2) || ((n > 1) && (n & 1));
        else
        {
            for( ;squares <= n; odd += 2)
            {
                if( n % odd == 0) 
                    return 0;
                squares+=odd;
            }
            return 1;
        }
    }
    

提交回复
热议问题