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