题目:打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。
例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。
程序分析:利用for循环控制100-999个数,每个数分解出个位,十位,百位。
代码如下:
l=[] #生成空列表 for n in range(100,1000): #for循环 i=n//100 #取整找出百位数 j=(n-i*100)//10 #取整找出十位数 k=(n-i*100-j*10) #找出个位数 if n==i**3+j**3+k**3: l.append(n) #满足条件添加到列表l print(l)
执行结果:
[153, 370, 371, 407]
思考:能不能求出所有的“水仙花数”???,而不是在(100,1000)之间的几个数
如果想要找到所有的“水仙花数”,那么每个位上的三次方等于这个数,肯定是有限的,那么最大的是多少位的数字呢?
我们可以用9的三次方乘以位数和这个数相比较,判断出这个数最大多少位是,超出这个位数的数字它的每个位的三次方之和永远不可能大于等于它
判断最大位数:
n=1 #n表示位数,初始值为1 while True: if n*(9**3)>10**n: #判断各个位数三次方与这个位数大小 n+=1 #位数加1 else: print("最大位数为:",n)
break #退出while循环
执行结果:
最大位数为: 4
所以,“水仙花数”最大不会超过1000
l=[] for number in range(0,1000): i=number//100 j=(number-i*100)//10 k=(number-i*100-j*10) if i**3+j**3+k**3==number: l.append(number) print("所有的水仙花数为:",l)
执行结果:
所有的水仙花数为: [0, 1, 153, 370, 371, 407]