How to find all happy numbers in a specific range with Python

1 Answer

0 votes
# A happy number is a number that eventually reaches 1 
# when repeatedly replaced by the sum of the squares of its digits.
#
# 19 = 1^2 + 9^2 = 82
# 19 -> 82 -> 68 -> 100 -> 1 eventually reaches 1 
# 19 = happy number

# Compute the sum of squares of digits of n
def sumOfDigitSquares(n):
    sum_ = 0
    while n > 0:
        d = n % 10
        sum_ += d * d
        n //= 10
    return sum_

# Determine whether n is a happy number
def isHappy(n):
    seen = set()

    while n != 1 and n not in seen:
        seen.add(n)
        n = sumOfDigitSquares(n)

    return n == 1

def main():
    a, b = 1, 100

    if a > b:
        a, b = b, a

    happyNumbers = []

    for i in range(a, b + 1):
        if isHappy(i):
            happyNumbers.append(i)

    print(f"Happy numbers in range [{a}, {b}]:")
    for n in happyNumbers:
        print(n, end=" ")
    print()

if __name__ == "__main__":
    main()


'''
run:

Happy numbers in range [1, 100]:
1 7 10 13 19 23 28 31 32 44 49 68 70 79 82 86 91 94 97 100 

'''

 



answered Feb 24 by avibootz
...