leetcode-507-Perfect Number

Topic description:

We define the Perfect Number is a positive integer that is equal to the sum of all its positive divisors except itself.

Now, given an integer n, write a function that returns true when it is a perfect number and false when it is not.

 

Example:

Input: 28
Output: True
Explanation: 28 = 1 + 2 + 4 + 7 + 14

 

Note: The input number n will not exceed 100,000,000. (1e8)

 

Function to be done:

bool checkPerfectNumber(int num)

 

illustrate:

1. Given a number, determine whether it is a perfect number. The definition of a perfect number is that the sum of all positive factors except itself is equal to the number itself.

2. Because the given number is limited to within 100 million, and it is completely within 100 million, only five are known...

So my friends know what to do...

code show as below:

   bool checkPerfectNumber(int num) 
    {
        if (num== 6 ||num== 28 ||num== 496 ||num== 8128 ||num== 33550336 )
             return  true ;
        else 
            return  false ;
    }

Measured 6ms, beats 81.37% of cpp submissions.

The known perfect number derivation formula is given by Euler: if p is a prime number and 2^p-1 is also a prime number, then (2^p-1)X2^(p-1) is a perfect number.

It can also be judged according to this condition, but as far as this problem is concerned, the above solution is the most direct.

 

3. Normal solution:

The normal solution must be brute force cracking. Find all positive factors except itself, and see if the sum will equal itself.

code show as below:

    bool checkPerfectNumber(int num) 
    {
        if (num== 1 )//num==1 is the boundary condition
             return  false ;
         int sum= 1 ;
         int up= sqrt(num);
         for ( int i= 2 ;i<=up;i++ )
        {
            if(num%i==0)
            {
                sum +=i+(num/i==i? 0 :num/ i);//This step needs to be judged, because for example 49/7=7
            } //We only need to add a factor of 7 at this time
        }
        if(sum==num)
            return true;
        else
            return false;
    }

The above code measured 10ms, beats 16.77% of cpp submissions.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325084695&siteId=291194637