O(logn * n^0.25) in C#


  • 0
    M

    Perfect numbers follow the pattern (2^p - 1)2^(p-1) where 2^p - 1 is a prime number.
    http://mathworld.wolfram.com/PerfectNumber.html

    public bool CheckPerfectNumber(int num)
    {
        int a = 2;
        while( num < a * (2 * a - 1)) a <<= 1;
    
        if (num != a * (2 * a - 1)) return false;
    
        int n = 2 * a - 1;
        for(int i = 3; i*i <= n; i += 2) if (n % i == 0) return false;
    
        return true;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.