In this blog we will create a program in c# for check entered number is perfect number or not.

What are Perfect Numbers?

Perfect numbers are the positive integers which are equal to the sum of its factors except the number itself. In other words, perfect numbers are the positive integers which are the sum of its proper divisors. The smallest perfect number is 6, which is the sum of its proper divisors: 1, 2 and 3.

Program to check whether a number is perfect number or not


Program to check perfect number







Code Explanation:

  • First we define three variables number type of integer, sum type of integer and divisors type of string. We use number for get input of user, sum for get sum of divisor and divisors for add all divisors of number in one string.
  • Then we get input from user and pass it to number variable by converting it to integer.
  • Then we iterate a loop from 1 (one) to number – 1.
  • In loop we module number by iterate variable I. If reminder is 0 then add that number in sum and concat value of I in our variable divisors with plus (+) sign.
  • After loop we remove last one character from divisors variable because extra one + is also concat in string. Here we just show this as all divisors sum is equal to sum for better user understanding.
  • Next we check sum is equal to user’s input. If yes then show message that entered number is perfect number otherwise entered number is not 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 code, the program will exit as soon as it is run.

Output

Program to check whether a number is perfect number or not

Program to check whether a number is perfect number or not



I hope you find this blog helpful. If you find any help from this blog share with your friends.