public static bool IsPerfectNumber(int n)
{
int sum = 0;
Console.Write("Factors:");
for (int i = 1; i < n; i++)
{
if (n % i == 0)
{
Console.Write($"{i} ");
sum = sum + i;
}
}
Console.WriteLine($"Sum: {sum}");
return sum == n ? true : false;
}
How it works:
While calculating the factors, we exclude the input number from the loop (the reason why the condition is i < n and not i <=n) and for each time the counter is a factor of the input number we add it to the sum. Finally, we compare the sum with the input number for equality and the result tells us if its a Perfect Number or not.
Number: 6
Factors:1 2 3 Sum: 6
True