KnowledgeBoat Logo
|

Robotics & Artificial Intelligence

A number is said to be 'Happy number' if eventual sum of the square of its digits results in 1. Write a Python code to input a number and check whether it is a Happy Number or not.

Sample Input: 31

Sample Output: 31 = 32 + 12 = 10 = 12 + 0 = 1

Hence, it is a Happy Number

Python Control Flow

1 Like

Answer

n = int(input("Enter a number: "))
p = n

while n > 9:
    s = 0
    while n > 0:
        d = n % 10
        s = s + d*d
        n = n // 10
    n = s

if n == 1:
    print(p, "is a Happy Number")
else:
    print(p, "is not a Happy Number")

Output

Enter a number: 31
31 is a Happy Number

Enter a number: 12
12 is not a Happy Number

Answered By

2 Likes


Related Questions