# Finding perfect numbers

### Description

**Perfect number **is a natural number where the sum of it’s dividers (without itself) is equal to that number. For example 6 and 28 are perfect numbers because

D_{6} = {1, 2, 3} and 6 = 3 + 2 + 1

D_{28} = {1, 2, 4, 7, 14} and 28 = 14 + 7 + 4 + 2 + 1

The obvious solution would be to check numbers from 1 to *n *and save the dividers. Then, we add all dividers to each other and check if it’s equal to *n*. It will work perfectly fine for small numbers like 6, 28 or 496 but imagine that you need to check if 137438691328 is perfect. It would take a lot of time and computer’s resources. Let me show you a better way. Let’s take our 28. You can find it’s all dividers doing only 3 mathematical operations instead of 6:

28 : 1 = 28

28 : 2 = 14

28 : 4 = 7

So, we can end our loop as soon as it will get to √28 and save the dividers along with results. Using this method we can cut necessary resources and time by half.

### Input data

A natural number *n*.

### Output data

- 1 if
*n*is perfect. - 0 if n isn’t perfect.

### C++ code

1 2 3 4 5 6 7 8 9 10 11 | bool isPerfectNumber(int n) { int sum = 1; //All natural numbers can be divided by 1, so sum is set to 1. for(int i=2; i*i<=n; i++) //The loop break condition is i*i<=n because we check numbers only to square of n. if(n%i == 0) // Checks if number can be divided by i without a remainder. sum+= i + n/i; // If yes then we add the divider and result to the sum. if(n == sum) return 1; return 0; } |