Perfect Numbers – and a best case algorithm
Brute Force Algorithm – O (N)
The brute force approach will loop through all the way from 1 to N – looking for divisors and add them to a running sum.
public boolean checkPerfectNumber(int num) { if (num <= 0) { return false; } int sum = 0; for (int i = 1; i * i <= num; i++) { if (num % i == 0) { sum += i; if (i * i != num) { sum += num / i; } } } return sum - num == num; } }
Only Loop till SqRt (N) – O(sqrt N)
There is no need to loop till N. Any divisor will need to be less than or equal to sqrt N. So – shorten the loop to only go till sqrt N.