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

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

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...