Skip to content

Instantly share code, notes, and snippets.

@wibus-wee
Last active November 3, 2022 01:43
Show Gist options
  • Save wibus-wee/e5329b48fcd9ed066e0cf94fc4f97f51 to your computer and use it in GitHub Desktop.
Save wibus-wee/e5329b48fcd9ed066e0cf94fc4f97f51 to your computer and use it in GitHub Desktop.
'''
FilePath: /nx-core/Users/wibus/Desktop/求水仙花数.py
author: Wibus
Date: 2022-06-25 16:42:54
LastEditors: Wibus
LastEditTime: 2022-06-25 19:38:36
Coding With IU
'''
# 求水仙花数
# 水仙花数是指一个 n 位数,它的每个位上的数字的 n 次幂之和等于它本身。
# 例如:153 是一个 3 位数,因为 1 的 3 次幂 + 5 的 3 次幂 + 3 的 3 次幂 = 153。
# 求出100-999之间的所有水仙花数
print("问题:若求出100-999之间的所有水仙花数")
# 方法一: 暴力解法
print("-----------------------------------------------------")
print("方法一: 暴力解法")
for i in range(100, 1000): # 循环100到1000的数字
a = int(i / 100) # 取出百位
b = int((i - a * 100) / 10) # 取出个位数
c = int(i - a * 100 - b * 10) # 求出每个位上的数字
if i == a ** 3 + b ** 3 + c ** 3: # 注意这里的等号,如果是水仙花数,则打印出来
print(i) # 输出水仙花数
print("-----------------------------------------------------")
# 方法二
print("方法二:抽离出来的方法")
def narcissistic(n): # n 为数字
a = int(n / 100) # 取出百位
b = int((n - a * 100) / 10) # 取出个位数
c = int(n - a * 100 - b * 10) # 求出每个位上的数字
if n == a ** 3 + b ** 3 + c ** 3: # 注意这里的等号
return n # 返回n的值
else:
return 0 # 如果不是水仙花数,返回0
print([n for n in range(100, 1000) if narcissistic(n)])
print("-----------------------------------------------------")
'''
上面全部的代码若运行,则会输出:
问题: 若求出100-999之间的所有水仙花数
-----------------------------------------------------
方法一: 暴力解法
153
370
371
407
-----------------------------------------------------
方法二:抽离出来的方法
[153, 370, 371, 407]
-----------------------------------------------------
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment