# Algorithm and Flowchart to check whether a number is Krishnamurthy number or not

[16641 views]

### What are Krishnamurthy numbers?

A number is said to be a Krishnamurthy number if the sum of the factorial of all its digits is equal to that number. They are sometimes also known as Peterson number or Strong number.

For example: Let us consider the number 145.
Factorial sum = 1! + 4! + 5! = 1 + 24 + 120 = 145
Other examples include: 1, 2, 40585.

Note: Factorial of a number is the product of all the consecutive numbers, starting from 1, till that number. It is denoted by ‘!’. Example: 5! = 1*2*3*4*5 = 120

Let us have a look at the algorithm and flowchart to check whether a given number is a Krishnamurthy number or not.

### Algorithm to check whether a number is Krishnamurthy number or not:

Step 1. Start Step 2. Read the number from the user Step 3. Initialize the factorial sum of the digits, s = 0 Step 4. Save a copy of the original number, temp = n Step 5. Repeat WHILE n ne 0: 5.1: Extract the last digit by: d = n % 10 5.2: Initialize loop variable, i = 2 5.3: Initialize the factorial, f = 1 5.4: Repeat until i <= d: 5.4.1: f = f * i 5.4.2: Increment ‘i’ by 1 5.5: Calculate sum by: s = s + f 5.6: Remove the last digit from the number: n = n / 10 Step 6. If s = temp: 6.1: Print "Krishnamurthy number" Step 7. Else: 7.1: Print "Not Krishnamurthy number" Step 8. Stop

### Explanation:

The algorithm starts by taking the number, say ‘n’, to be checked as user input. To check whether a number is Krishnamurthy or not, we will have to calculate the sum of the factorial of each digit. In simple words, we will extract each digit from the number and calculate its factorial, and then add it to the sum.

We will save a copy of the given number in a variable ‘temp’ and initialize the sum ‘s’ to be 0. After this, we will start a while loop, which runs until the number is not equal to zero. We will then extract the last digit of the number by performing: d = n % 10. After that the factorial of the digit is initialized as 1 and a for loop is started from 2 to d. (Note that we are staring the loop for factorial from 2 since we have already initialized the factorial as 1. In case the given number is 1, we will never enter the loop and the factorial will be 1.) After the factorial is calculated, we will add the factorial to the sum.

Once we are out of the while loop, we will check whether the sum and the original number are equal or not. If yes, the given number is Krishnamurthy number, else it is not a Krishnamurthy number.

If we take the example of the number 145;
temp = 145
s= 1! + 4! + 5! = 1 + 24 +120 = 145
Here, sum = temp.
Hence, 145 is a Krishnamurthy number.
Note: Here ‘%’ is the modulus operator which returns the remainder value after division.