A Python implementation to check whether the input number is a Krishnamurthy number (a number that is equal to the sum of the factorial of each of its digits) or not.

Hey CodeSpeeder!

Numbers are amazing when it comes to finding patterns within the number themselves.

Consider a number, for example, 145. There are a total of 3 digits in the number: 1, 4, and 5 whose factorial is 1, 24, and 120 respectively. Add them up and you'll get 145, the input number again. Isn't this fascinating! Such numbers are specially named as **Krishnamurthy number**, **Strong number, **or **Peterson number***. *

Let's mathematically formulate this! Consider a number **num** with n digits be expressed as d_{n}d_{n-1}...d_{1}. **num** is a Krishnamurthy number if the following condition is satisfied:

**d _{n}d_{n-1}...d_{1} = d_{n}!_{ }+ d_{n-1}!^{ }+...+ d_{1}!**

For example:

Number 145 is a 3-digit number. From the above condition, LHS=145 while RHS = 1!^{ }+ 5!^{ }+4! = 145 = LHS. 145 is a Krishnamurthy number.

Number 154 is also a 3-digit number. Here, LHS=154 while RHS = 1!^{ }+ 5!^{ }+4! = 145. Hence, 154 is not a Krishnamurthy number.

The following is the **Python** implementation for checking whether the input number is a Krishnamurthy number or not:

import math # function to check if the number n # is Krishnamurthy number or not def isKrishnamurthyNumber(num): sumVal = 0 # Sum value # calculate the sum of the factorial of each digit in number num for digit in str(num): sumVal += math.factorial(int(digit)) # if the sumVal is equal to input number num, # num is an Krishnamurthy number if sumVal == num: return True else: return False

The below is the driver code to check the function** isKrishnamurthyNumber()** on various test-cases:

# Test-case 1: 1 is a Krishnamurthy number print("Is 1 a Krishnamurthy Number? - ", isKrishnamurthyNumber(1)) # Test-case 2: 2is not a Krishnamurthy number print("Is 2 a Krishnamurthy Number? - ", isKrishnamurthyNumber(2)) # Test-case 3: 145 is a Krishnamurthy number print("Is 145 a Krishnamurthy Number? - ", isKrishnamurthyNumber(145)) # Test-case 4: 154 is not a Krishnamurthy number print("Is 154 a Krishnamurthy Number? - ", isKrishnamurthyNumber(154)) # Test-case 5: 40585 is a Krishnamurthy number print("Is 40585 a Krishnamurthy Number? - ", isKrishnamurthyNumber(40585))

The output of the following code is:

Is 1 a Krishnamurthy Number? - True Is 2 a Krishnamurthy Number? - True Is 145 a Krishnamurthy Number? - True Is 154 a Krishnamurthy Number? - False Is 40585 a Krishnamurthy Number? - True

There are exactly four Krishnamurthy numbers which are 1, 2, 145, and 40585 at present known.

Submitted by Kalki Pareshkumar Bhavsar (KalkiBhavsar)

Download packets of source code on Coders Packet