A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. A divisor of an integer x is an integer that can divide x evenly.
Given an integer n, return true if n is a perfect number, otherwise return false.
Example 1:
Input: num = 28 Output: true Explanation: 28 = 1 + 2 + 4 + 7 + 14 1, 2, 4, 7, and 14 are all divisors of 28.
Example 2:
Input: num = 7 Output: false
Constraints:
1 <= num <= 108The main idea is that divisors come in pairs, and for each pair (d, n/d), if d is less than the square root of n, then d and n/d are both divisors of n. This approach allows us to only iterate up to the square root of n, making it more efficient.
The function first checks if num is less than or equal to 1, returning false if so, as there's no perfect number <= 1. Then it initializes sum with 1 since 1 is a divisor of every number except itself. We iterate through possible divisors up to the square root of num. If i is a divisor, we add it and its pair num/i to sum, avoiding double counting. Finally, we check if sum equals num.
C++
Java
Python
C#
JavaScript
Time Complexity: O(sqrt(n))
Space Complexity: O(1)
This approach calculates the sum of all divisors excluding the number itself by checking each integer from 1 to n-1 to determine if it's a divisor, then sums these and checks if the sum equals n. This method is simple but inefficient for large numbers.
The C solution performs a simple loop through possible divisors from 1 to num - 1, summing any divisors found and checking if this total matches num.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n)
Space Complexity: O(1)
| Approach | Complexity |
|---|---|
| Optimized Divisor Sum with Square Root Iteration | Time Complexity: O(sqrt(n)) |
| Naive Divisor Sum | Time Complexity: O(n) |
Microsoft Coding Interview Question - Valid Perfect Square - Leetcode 367 • Greg Hogg • 1,026,523 views views
Watch 9 more video solutions →Practice Perfect Number with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor