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.
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.
Output:
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.