当停车时数不快乐的数快乐、时数不

2023-09-11 02:44:14 作者:空笑

有一个幸福的数量由以下方法确定。与任何正整数开始,由它的位数的平方和替换的数目,并重复该过程,直到数量等于1

但是,当一些不愉快数它无休止地循环,在一个周期中不包括:1。

我在蟒蛇codeD开心一些问题,但问题是,当一些不开心的话,我怎么可能停止迭代周期。因为它不会与1结束,将继续重演。

 高清happynumber(数字):

而(数量= 1!):
    numberstr = STR(数字)#converting一个数字,字符串
    指数= 0
    总和= 0
    而(指数= LEN(numberstr)!):
        总和=总和+ INT(numberstr [指数])* INT(numberstr [指数])
        指数=指数+ 1
    打印总和

    数= SUM
回数
 

解决方案 最新 银川市行政中心机关内部停车场115个泊位免费向社会开放

可以检测出不高兴的数字与内存了一定量。据维基百科,对于任意正整数的起点,该序列将终止在一个或永远循环下去,在 4,16,37,58,89,145,42,20,4 。因为没有其他环路存在,很容易测试对于不快。

 高清isHappy(X):
    而真正的:
        如果x == 1:
            返回True
        如果x == 4:
            返回False
        X = nextNumberInSequence(X)
 

A happy number is defined by the following process. Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1.

But when number is not a happy number it loops endlessly in a cycle which does not include 1.

i have coded happy number problem in python but the problem is when a number is not happy , then how could i stop the iterating cycle. since it will not end with 1 and will keep on repeating itself.

def happynumber(number):

while(number!=1):
    numberstr = str(number) #converting a number to string
    index=0 
    sum=0
    while(index!=len(numberstr)):
        sum = sum + int(numberstr[index])*int(numberstr[index])
        index = index+1
    print sum

    number = sum
return number

解决方案

You can detect unhappy numbers with a constant amount of memory. According to Wikipedia, for any positive integer starting point, the sequence will terminate at one, or loop forever at 4, 16, 37, 58, 89, 145, 42, 20, 4. Since no other loops exist, it is easy to test for unhappiness.

def isHappy(x):
    while True:
        if x == 1:
            return True
        if x == 4:
            return False
        x = nextNumberInSequence(x)