1. 快乐的数字
编写一个算法来确定一个数字是否“快乐”。 快乐的数字按照如下方式确定:从一个正整数开始,用其每位数的平方之和取代该数,并重复这个过程,直到最后数字要么收敛等于 1 且一直等于 1,要么将无休止地循环下去且最终不会收敛等于 1。能够最终收敛等于 1 的数就是快乐的数字。
例如: 19 就是一个快乐的数字,计算过程如下:
1 ** 2 + 9 ** 2 = 82
8 ** 2 + 2 ** 2 = 68
6 ** 2 + 8 ** 2 = 100
1 ** 2 + 0 ** 2 + 0 ** 2 = 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| def func(a): s = 0 while(a>0): rest = a % 10 s = s + rest * rest a = a // 10 return s
def main(): inputStr = input() try: integer = eval(inputStr) except: print(False) else: i = 0 while( i < 1000 and integer != 1): integer = func(integer) i += 1 if i<1000 and integer ==1: print(True) else: print(False)
main()
|