In this post, we will learn how to check a happy number. A number is called a happy number if it will yield 1 when it replaced by the sum of the squares of its digits repeatedly.
Implementation Using Java:
import java.util.Scanner;
public class HappyNumber {
public static void checkHappy(int n)
{
while(n!=1)
{
int sum=0;
while(n!=0)
{
int temp=n%10;
sum=sum+(temp*temp);
n=n/10;
}
n=sum;
}
if(n==1)
{
System.out.println("It is happy number");
}
else
{
System.out.println("It is not happy number");
}
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number:");
int n=sc.nextInt();
checkHappy(n);
}
}
Output:
Enter the number:91
It is Happy number
Happy Coding!
Follow us on Instagram @programmersdoor
Join us on Telegram @programmersdoor
Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem.
Follow Programmers Door for more.
Comments