Question
Check whether a number is Happy Number
A number is called happy if it leads to 1 after a sequence of steps wherein each step number is replaced by the sum of squares of its digit that is if we start with Happy Number and keep replacing it with digits square sum, we reach 1.
Input: n = 19
Output: True
19 is Happy Number,
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
As we reached to 1, 19 is a Happy Number.
Example 2:
Enter a non-zero Positive Number:13
It is a Happy Number
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
Java
Python
Java
import java.util.*;
public class HappyNumber
{
/* calculate the sum of squares of each digits*/
public static int SumOfSquareOfDigits (int number)
{
int rem = 0, sum = 0;
while(number > 0)
{
rem = number %10;
sum = sum+(rem*rem);
number = number/10;
}
return sum;
}
public static void main(String[] args)
{
/* Take number from user*/
int result = 0;
boolean flag=true;
Scanner sc = new Scanner (System.in);
System.out.print("Enter a non-zero Positive Number:");
int num = sc.nextInt();
if(num <= 0)
{
System.out.println("Number is not a happy number");
}
else
{
result=num;
while(flag==true)
{
result = SumOfSquareOfDigits(result);
if(result==1)
{
System.out.println (num+" is a Happy Number");
flag=false;
}
else if(result==4)
{
System.out.println (num+" is not a Happy Number");
flag=false;
}
}
}
}
}
Python
number=int(input("Enter a number:"))
if(number<=0):
print(number,"is not a Happy number")
else:
result=number
while(result != 1 and result != 4):
temp=result
sum=0
while(temp>0):
rem=temp%10
sum=sum+(rem*rem)
temp=temp//10
result=sum
if(result==1):
print(number,"is a Happy number")
else:
print(number,"is not a Happy number")