Python 阿姆斯特朗数
Python 3 教程
· 2019-02-12 12:44:38
如果一个n位正整数等于其各位数字的n次方之和,则称该数为阿姆斯特朗数。 例如1^3 + 5^3 + 3^3 = 153。
1000以内的阿姆斯特朗数: 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407。
以下代码用于检测用户输入的数字是否为阿姆斯特朗数:
实例(Python 3.0+)
# Filename : test.py
# author by : www.codercto.com
# Python 检测用户输入的数字是否为阿姆斯特朗数
# 获取用户输入的数字
num = int(input("请输入一个数字: "))
# 初始化变量 sum
sum = 0
# 指数
n = len(str(num))
# 检测
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** n
temp //= 10
# 输出结果
if num == sum:
print(num,"是阿姆斯特朗数")
else:
print(num,"不是阿姆斯特朗数")
执行以上代码输出结果为:
$ python3 test.py 请输入一个数字: 345 345 不是阿姆斯特朗数 $ python3 test.py 请输入一个数字: 153 153 是阿姆斯特朗数 $ python3 test.py 请输入一个数字: 1634 1634 是阿姆斯特朗数
获取指定期间内的阿姆斯特朗数
实例(Python 3.0+)
# Filename :test.py
# author by : www.codercto.com
# 获取用户输入数字
lower = int(input("最小值: "))
upper = int(input("最大值: "))
for num in range(lower,upper + 1):
# 初始化 sum
sum = 0
# 指数
n = len(str(num))
# 检测
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** n
temp //= 10
if num == sum:
print(num)
执行以上代码输出结果为:
最小值: 1 最大值: 10000 1 2 3 4 5 6 7 8 9 153 370 371 407 1634 8208 9474
以上实例中我们输出了 1 到 10000 之间的阿姆斯特朗数。
点击查看所有 Python 3 教程 文章: https://www.codercto.com/courses/l/10.html
Coding the Matrix
Philip N. Klein / Newtonian Press / 2013-7-26 / $35.00
An engaging introduction to vectors and matrices and the algorithms that operate on them, intended for the student who knows how to program. Mathematical concepts and computational problems are motiva......一起来看看 《Coding the Matrix》 这本书的介绍吧!