Get All Perfect Numbers In A Range Of Two Numbers

In this blog we will create a C# program for finding all perfect numbers between two numbers. Here we  will get two inputs from user and then perform an operation on it.
Also check out: 
In the above blog I had covered what is the perfect number and how to check if any number is perfect or not . 
Program to find all perfect numbers in range:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  7. namespace PerfectNumberInRange  
  8. {  
  9.     class Program  
  10.     {  
  11.         static void Main(string[] args)  
  12.         {  
  13.             int startingNumber, endingNumbeer;  
  14.             Console.WriteLine("Get All Perfect In Range of Between two Number");  
  15.             Console.Write("Enter Starting Number : ");  
  16.             startingNumber = int.Parse(Console.ReadLine());  
  17.             Console.Write("Enter Ending Number : ");  
  18.             endingNumbeer = int.Parse(Console.ReadLine());  
  20.             Console.WriteLine("Below are the perfect number between " + startingNumber + " and " + endingNumbeer);  
  22.             for (int i = startingNumber; i <= endingNumbeer; i++)  
  23.             {  
  24.                 decimal sum = 0;  
  25.                 for (int j = 1; j < i; j++)  
  26.                 {  
  27.                     if (i % j == 0)  
  28.                         sum = sum + j;  
  29.                 }  
  30.                 if (sum == i)  
  31.                     Console.WriteLine("\t" +i);  
  32.             }  
  34.             Console.ReadKey();  
  35.         }  
  36.     }  
  37. }  
Get All Perfect Number In A Range Of Two Numbers
Get All Perfect Number In A Range Of Two Numbers
  • Here we get two inputs from user, a starting number and ending number.
  • Then we iterate loop from starting number to ending number.
  • In this loop iterate another loop from 1 to the value of parent loop and declare a new variable called sum and assign zero to it.
  • In child loop we modulate parent loop value with child loop value. If value is equal to zero then add that value in sum variable.
  • After child loop completes, check if sum value and parent loop value both are equal or not. If both values are equal then this number is a perfect number.
  • Then we use the Console.ReadKey() method to read any key from the console. By entering this line of code, the program will wait and not exit immediately. The program will wait for the user to enter any key before finally exiting. If you don't include this statement in the code, the program will exit as soon as it is run.
I hope you find this blog helpful. If you get any help from this blog please share it with your friends.