The idea is to add up the proper divisors of n. Here is a pre-simulation of that for n = 6 where, in each row, 'sum' is the sum of the proper divisors of n up to and including i.
n i sum i a proper divisor of n?
6 1 1 yes
2 3 yes
3 6 yes
4 6 no
5 6 no
6 6 no
So the sum of the proper divisors of 6 is 6. Here is a pre-simulation for n = 8.
n i sum i a proper divisor of n?
8 1 1 yes
2 3 yes
3 3 no
4 7 yes
5 7 no
6 7 no
7 7 no
8 7 no
So the sum of the proper divisors of 8 is 7. It should be clear that
sum = 1; i = 1;initializes sum and i correctly. Update of i is just
i++;To update sum, we need to check whether n % i == 0. Looking at adjacent lines
n i sum i a proper divisor of n?
6 2 3 yes
3 6 yes
and
n i sum i a proper divisor of n?
6 3 6 yes
4 6 no
it is clear that the value of i after i is updated
should be added to sum, provided n % i == 0.
When i = 2, we see that 3 is a factor of 6, so we add 3 to sum.
When i = 3, we see that
4 is not a factor of 6, so we don't change sum.
Here is a definition of isPerfect based on those pre-simulations.
bool isPerfect(const int n)
{
int sum = 1;
int i = 1;
while(i < n)
{
i++;
if(n % i == 0)
{
sum = sum + i;
}
}
return (sum == n);
}