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
Ram
Ram

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity. You can connect with me on Medium, Twitter or LinkedIn.

Privacy Overview
Referbruv

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookies

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

3rd Party Cookies

This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

Keeping this cookie enabled helps us to improve our website.