写一个 Python示例,使用 While 循环、For 循环和阶乘函数查找强数,并给出一个例子。
这个 python 程序用于一个强数,允许用户输入任意正整数。接下来,Python 使用 While 循环检查给定的数字是否是强数。
# Python Program to find Strong Number
Number = int(input(" Please Enter any Number: "))
Sum = 0
Temp = Number
while(Temp > 0):
Factorial = 1
i = 1
Reminder = Temp % 10
while(i <= Reminder):
Factorial = Factorial * i
i = i + 1
print("\n Factorial of %d = %d" %(Reminder, Factorial))
Sum = Sum + Factorial
Temp = Temp // 10
print("\n Sum of Factorials of a Given Number %d = %d" %(Number, Sum))
if (Sum == Number):
print(" %d is a Strong Number" %Number)
else:
print(" %d is not a Strong Number" %Number)
在这个 Python 强数示例中,首先,我们将原始值赋给 Temp 变量。它帮助我们保持我们的原始价值。
第一个 While Loop 确保给定的数字大于 0。while 循环中的语句拆分数字,并找出给定数字中各个数字的阶乘。请参考 Python 数数文章了解逻辑。
第二个 While 循环(嵌套循环)查找每个数字的阶乘。建议大家参考 Python 查找一个数的阶乘文章,了解阶乘背后的逻辑。
用户为此 Python示例输入的值,以查找强数:数字= 145,总和= 0 因数 1 = 1,i = 1 温度=数字 温度= 145
Python示例在循环时首先查找强名称–第一次迭代 提醒= Temp % 10 提醒= 145 % 10 = 5
现在,它进入 Python 内部或嵌套 While 循环。这里,它计算 5 = 120 的阶乘。
总和=总和+120 => 0 + 120 总和= 120
温度=温度//10 => 145 //10 温度= 14
第二次迭代 温度= 14,总和= 120 提醒= 14 % 10 = 4
现在,它进入内部 While 循环。这里,它计算 4 = 24 的阶乘。
总和= 120 + 24 总和= 144
Temp = 14/10 Temp = 1
第三次迭代 温度= 1,总和= 144 提醒= 1 % 10 = 0
这里,1 的阶乘是 1 和= 144 + 1 和= 145
Temp = 1/10 Temp = 0
这里 Temp = 0,所以 while 循环条件失败。
if(Number = = Sum)–条件检查用户输入的数字是否完全等于 Sum。如果这个条件为真,那么它就是强数,否则它不是强数。
这个针对 Python 强数的程序同上。在这个 python 程序中,我们将 While 循环替换为 For 循环。
Number = int(input(" Please Enter any Number: "))
Sum = 0
Temp = Number
while(Temp > 0):
Factorial = 1
Reminder = Temp % 10
for i in range(1, Reminder + 1):
Factorial = Factorial * i
print("Factorial of %d = %d" %(Reminder, Factorial))
Sum = Sum + Factorial
Temp = Temp // 10
print("\n Sum of Factorials of a Given Number %d = %d" %(Number, Sum))
if (Sum == Number):
print(" %d is a Strong Number" %Number)
else:
print(" %d is not a Strong Number" %Number)
Please Enter any Number: 40585
Factorial of 5 = 120
Factorial of 8 = 40320
Factorial of 5 = 120
Factorial of 0 = 1
Factorial of 4 = 24
Sum of Factorials of a Given Number 40585 = 40585
40585 is a Strong Number
这个 Python 强数程序和第一个例子一样。然而,我们正在使用一个名为阶乘的内置数学函数来寻找阶乘。这种方法消除了嵌套 while 循环。
import math
Number = int(input(" Please Enter any Number: "))
Sum = 0
Temp = Number
while(Temp > 0):
Reminder = Temp % 10
Factorial = math.factorial(Reminder)
print("Factorial of %d = %d" %(Reminder, Factorial))
Sum = Sum + Factorial
Temp = Temp // 10
print("\n Sum of Factorials of a Given Number %d = %d" %(Number, Sum))
if (Sum == Number):
print(" %d is a Strong Number" %Number)
else:
print(" %d is not a Strong Number" %Number)
使用阶乘输出的 Python 强数。
Please Enter any Number: 145
Factorial of 5 = 120
Factorial of 4 = 24
Factorial of 1 = 1
Sum of Factorials of a Given Number 145 = 145
145 is a Strong Number
标签: 乐酷