Python Program To Check Happy number or Not
In Number Theory, A Happy Number is a Number Which
Eventually reaches 1 when replaced by the sum of the square of each digit.
Example :
Given Number : 13
13 is a Happy Number
Because
13 = ( 1*1 )+( 3*3 ) = 1 + 9 = 10
10 = ( 1*1 )+( 0*0 ) = 1 + 0 = 1
Given Number : 28
28 is a Happy Number
Because
28 = ( 2*2 ) +( 8*8 ) = 4 + 64 = 68
68 = ( 6*6 ) +( 8*8 ) = 36+ 64 = 100
100= ( 1*1)+( 0*0 )+ ( 0*0) = 1 + 0 + 0 = 1
you can use the following algorithm:
- Read the input number.
- Initialize a variable sum to 0.
- Create a copy of the input number.
- While num is not equal to 0, perform the following steps:
- Get the last digit of the num by using the modulo operator (%).
- Square the last digit and add it to sum.
- Divide the num by 10 to remove the last digit.
- if num = 0 and sum>=10
- Reset num to sum and sum to 0.
- Check if the sum of the number is equal to 1.
- If it is 1, the number is a Happy Number.
- If it is Not 1, the number is Not a Happy Number.
Please note that this implementation assumes that the input number is a positive integer. You may need to add additional checks for negative numbers or other cases depending on your requirements.
Here is an example implementation in Python:Source Code
# Python Program to Check Happy Number or Not
num = int(input("Enter a Number To Check : "))
Sum=0
while num!=0:
Rd = num%10
Sum=Sum+Rd**2
num=num//10
if num==0 and Sum>9:
num=Sum
Sum=0
if Sum==1:
print("It is a Happy Number . ")
else:
print("It is Not a Happy Number . ")
Output
Sample Input :
Enter a Number To Check : 28
Sample Output:
It is a Happy Number
Sample Input :
Enter a Number To Check : 13
Sample Output:
It is Not a Happy Number
Sample Input :
Enter a Number To Check : 12
Sample Output:
It is Not a Happy Number