Problem
题目大意:判断一个数的因数和是不是等于它本身。
https://leetcode.com/problems/perfect-number/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)
Solution: Brute Force
Try allnumbers from 1 to n – 1.
Time complexity: O(n) TLE for prime numbers
Space complexity: O(1)
Solution: Math
Try all numbers from 2 to sqrt(n).
If number i is a divisor of n then n/i is another one.
Be careful about the case when i == n/i, only one should be added to the sum.
Time complexity: O(sqrt(n))
Space complexity: O(1)
C++
1 2 3 4 5 6 7 8 9 10 11 12 |
// Author: Huahua // Running time: 6 ms class Solution { public: bool checkPerfectNumber(int num) { if (num <= 1) return false; int sum = 1; for (int i = 2; i <= sqrt(num); ++i) if (num % i == 0) sum += i + ((i == num / i) ? 0 : num / i); return sum == num; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment