使用 while 循环编写一个 Python 程序来检查数字是否为克里希那穆提数。如果一个数的各位数字的阶乘之和等于它本身,那么这个数就是克里希那穆提数。在这个 Python 示例中,我们使用 while 循环将数字分解为各位数字。接下来,math factorial 函数计算每个数字的阶乘。if 条件语句检查各位数字的阶乘之和是否等于该数字。如果为真,则该数字是克里希那穆提数。
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)

在这个 Python 示例中,我们移除了 math factorial 函数,并使用嵌套的 while 循环来检查该数字是否为克里希那穆提数。
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.