Perfect Number
Problem
A perfect number is equal to the sum of its divisors that are smaller than the number. Example: 6 = 1 + 2 + 3. Read an integer and print true if it is a perfect number, otherwise print false.
Constraints
- 0 <= n <= 10^12
Examples
Input
6
Output
true
Input
12
Output
false
Solutions
Divisors come in pairs (d and n / d). Testing only up to the square root finds both numbers of each pair, so the loop is much shorter.
/*
* Problem : Check if a number is a perfect number.
* Input : One integer.
* Output : true or false.
* Approach: Add all divisors smaller than the number.
* Time : O(sqrt(n))
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method receives a number and returns true if the number is a perfect number.
static boolean isPerfect(long number) {
// Step 1: Numbers smaller than 2 are not perfect.
if (number < 2) {
return false;
}
// Step 2: The divisor 1 divides every number, so the sum starts at 1.
long sum = 1;
// Step 3: Divisors come in pairs: if i divides n, then n / i divides n too. So we only test i up to the square root.
for (long divisor = 2; divisor * divisor <= number; divisor++) {
if (number % divisor == 0) {
// Step 4: Add the small divisor of the pair.
sum = sum + divisor;
// Step 5: Add the large divisor of the pair, but do not add the same number twice (for example 6 * 6 = 36).
long partner = number / divisor;
if (partner != divisor) {
sum = sum + partner;
}
}
}
// Step 6: A perfect number is equal to the sum of its divisors (without the number itself).
return sum == number;
}
public static void main(String[] args) {
long number = new Scanner(System.in).nextLong();
System.out.println(isPerfect(number));
}
}
Hints (2)
- If 2 divides n, then n / 2 divides n too.
- Stop the loop when divisor * divisor is larger than n.