C# programs to check if a number is a perfect number or not have been shown here. A perfect number is a positive integer that is equal to the sum of its proper divisors. For example 6 is a perfect number because if we add it's proper divisors (1, 2 and 3), we get 6 i.e. 1 + 2 + 3 = 6. Some of the other perfect numbers are 28, 496, 8128 etc.
Page content(s):
1. Algorithm to check if a number is a perfect number or not
1. Take a number n as input.
2. Set s = 0, x = 1
3. Check if n is divisible by x
4. If step 3 is true perform s = s + x
5. Set x = x + 1
6. Go step 3 until x > n/2
7. If s = n declare "n is a perfect number"
2. Pseudocode to check if a number is a perfect number or not
Input : A positive number n
Output : n is a perfect number or not
1. Procedure isPerfectNumber(n):
2.
3.
4.
5.
6.
7.
8.
9.
10.
11. End Procedure
3. Time complexity to check if a number is a perfect number or not
Time Complexity: O(n)
n is the input number
4. Program & Output to check if a number is a perfect number or not
4.1. C# Program & Output to check if a number is a perfect number or not using iteration
/************************** alphabetacoder.com C# program to check if a number is a perfect number ***************************/ using System; namespace PerfectNumber { class Program { static void Main(string[] args) { // declare variables int n, i, sum = 0; // take input of the number Console.Write("Enter the number: "); n = Convert.ToInt32(Console.ReadLine()); // add all the divisor upto n / 2 for (i = 1; i <= (n / 2); i++) { if (n % i == 0) sum = sum + i; } // check if the input number // is equal to the sum if (n == sum) Console.WriteLine(n + " is a perfect number"); else Console.WriteLine(n + " is not a perfect number"); // wait for user to press any key Console.ReadKey(); } } }
Output
Enter the number: 28
28 is a perfect number
4.2. C# Program & Output to check if a number is a perfect number or not using recursion
/************************************ alphabetacoder.com C# program to check if a number is a perfect number using recursion *************************************/ using System; namespace PerfectNumber { class Program { // recursive function to check if input // number is a perfect number or not public static int isPerfect(int n, int i, int sum) { if (i > n / 2) // exit condition return (sum == n) ? 1 : 0; if (n % i == 0) // check divisibility sum += i; return isPerfect(n, i + 1, sum); } static void Main(string[] args) { // declare variables int n; // take input of the number Console.Write("Enter the number: "); n = Convert.ToInt32(Console.ReadLine()); // check if the input number is perfect // by calling function if (isPerfect(n, 1, 0) == 1) Console.WriteLine(n + " is a perfect number"); else Console.WriteLine(n + " is not a perfect number"); // wait for user to press any key Console.ReadKey(); } } }
Output
Enter the number: 6
6 is a perfect number