Find if the given number is a Perfect Number

A Perfect Number is a positive integer for which the sum of all of its positive factors except the number results in the number itself. For example, 6 is a perfect number because the factors of 6 excluding itself are 1, 2, 3 and sum of them is itself - 6.

To achieve this, we shall make use of the factors logic and find the sum of all factors except the number itself and check if the sum is equal to the number or not.


        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
Default image
Sriram Mannava

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity.

Leave a Reply