Write a Python program to check the number is a Krishnamurthy number or not using a while loop. Any number is a Krishnamurthy number if the sum of the factorial of its digits equals itself. In this Python example, we used the while loop to divide the number into digits. Next, the math factorial function finds the factorial of each digit. The if condition checks whether the sum of the factorial of individual digits equals a number. If true, it is a Krishnamurthy number.
import math Number = int(input("Enter the Number to Check Krishnamurthy Number = ")) Temp = Number Sum = 0 while Temp > 0: fact = 1 i = 1 rem = Temp % 10 fact = math.factorial(rem) Sum = Sum + fact Temp = Temp // 10 if Sum == Number: print("\n%d is a Krishnamurthy Number." %Number) else: print("%d is Not a Krishnamurthy Number." %Number)
In this Python example, we removed the math factorial function and used the nested while loops to check the number is a Krishnamurthy number or not.
Number = int(input("Enter the Number to Check Krishnamurthy Number = ")) Sum = 0 Temp = Number while Temp > 0: fact = 1 i = 1 rem = Temp % 10 while i <= rem: fact = fact * i i = i + 1 print('Factorial of %d = %d' %(rem, fact)) Sum = Sum + fact Temp = Temp // 10 print("The Sum of the Digits Factorials = %d" %Sum) if Sum == Number: print("\n%d is a Krishnamurthy Number." %Number) else: print("%d is Not a Krishnamurthy Number." %Number)
Enter the Number to Check Krishnamurthy Number = 40585
Factorial of 5 = 120
Factorial of 8 = 40320
Factorial of 5 = 120
Factorial of 0 = 1
Factorial of 4 = 24
The Sum of the Digits Factorials = 40585
40585 is a Krishnamurthy Number.