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

Here, we are going to learn how to check the given number is a perfect number or not in C#?
Submitted by Nidhi, on September 21, 2020

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

Perfect Number: A positive integer number that is equal to the sum of its proper divisor.

Example:

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

Program:

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");
        else
            Console.WriteLine("Given number is not perfect number");
    }
}

Output:

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

Explanation:

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.