本文使用 Python 代码实现 100-500 范围内的水仙花数,水仙花数是指一个三位数,它的每个位上的数字的 3 次幂之和等于它本身,例如: 1^3 + 5^3+ 3^3 = 153。下面是输出 100-500 范围内的所有水仙花数的 Python 代码:

for num in range(100, 501):
    digit_sum = 0
    temp = num
    while temp > 0:
        digit = temp % 10
        digit_sum += digit ** 3
        temp //= 10
    if num == digit_sum:
        print(num)

运行结果为:

153 370 371 407

Python 代码实现 100-500 范围内的水仙花数

原文地址: https://www.cveoy.top/t/topic/oKSo 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录