編寫一個 Python 程序來檢查這個數字是不是一個 Krishnamurthy 數字,或者是否使用 while 循環。如果數的階乘之和等於它自己,那麼任何數都是 Krishnamurthy 數。在這個 Python 例子中,我們使用 while 循環將數字分成數字。接下來,數學階乘函數找到每個數字的階乘。if 條件檢查單個數字的階乘之和是否等於一個數字。如果是真的,這是一個 Krishnamurthy 數字。
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 示例中,我們移除了數學階乘函數,並使用嵌套的 while 循環來檢查該數是否是 Krishnamurthy 數。
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.
原創文章,作者:簡單一點,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/130064.html