C# Program to Check Whether a Given Number is Perfect Number

In this example, we will create a C# program to determine whether a given number is a perfect number, demonstrating the language’s ability to handle mathematical operations and conditional checks.

Problem Statement

Write a C# program to check whether a given positive integer is a perfect number. A perfect number is a positive integer that is equal to the sum of its proper divisors (excluding itself). For example, 28 is a perfect number because the sum of its divisors (1, 2, 4, 7, 14) is equal to 28.

C# Program to Check Whether a Given Number is Perfect Number

using System;

class Program
{
    static void Main()
    {
        Console.Write("Enter a positive integer: ");
        int number = Convert.ToInt32(Console.ReadLine());

        if (IsPerfectNumber(number))
        {
            Console.WriteLine(number + " is a perfect number.");
        }
        else
        {
            Console.WriteLine(number + " is not a perfect number.");
        }
    }

    static bool IsPerfectNumber(int num)
    {
        if (num <= 0)
        {
            return false;
        }

        int sumOfDivisors = 0;
        for (int divisor = 1; divisor < num; divisor++)
        {
            if (num % divisor == 0)
            {
                sumOfDivisors += divisor;
            }
        }

        return sumOfDivisors == num;
    }
}

Input / Output

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...