C# program to check perfect number

Here, we are going to learn how to check the given number is a perfect number or not in C#? By Nidhi Last updated : April 15, 2023

Perfect Number

In number theory, a perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. For instance, 6 has divisors 1, 2 and 3 (excluding itself), and 1 + 2 + 3 = 6, so 6 is a perfect number. [Source]


Given number: 6
Divisors of 6 are: 3,2,1
Sum of divisors: 6
So that 6 is a perfect number.

Checking Perfect Number

Here we will enter an integer number from the keyboard and check the given number is the perfect number or not.

C# code for checking perfect number

The source code to check the given number is a perfect number or not, is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to check the given number is a 
//perfect number or not.

using System;

class CheckPerfect
    static bool IsPerfect(int number)
        int sum     = 0;
        int iLoop   = 0;

        for (iLoop = 1; iLoop < number; iLoop++)
            if (number % iLoop == 0)
                sum = sum + iLoop;

        if (sum == number)
            return true;
        return false;
    static void Main(string[] args)
        int     number  = 0     ;
        bool    ret     = false ;

        Console.Write("Enter the integer number: ");
        number = int.Parse(Console.ReadLine());

        ret = IsPerfect(number);

        if (ret)
            Console.WriteLine("Given number is perfect number");
            Console.WriteLine("Given number is not perfect number");


Enter the integer number: 6
Given number is perfect number
Press any key to continue . . .


Here, we created a class CheckPerfect that contains two static methods IsPerfect() and Main().

The IsPerfect() method is used to check the given number is perfect or not. Here we find the sum of all divisors of a given number and check the sum of divisors with the number, if both are equal then we return value "true" to the calling method otherwise false will be returned to the calling method.

In the Main() method, we read a positive integer value and then pass the entered number to the IsPerfect() method and then print the appropriate message according to the return value of the IsPerfact() method.

C# Basic Programs »

Related Programs

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.