Blog

Happy Numbers in Java

Developed a program for finding out Happy Numbers from a given range of numbers. What is a Happy Number?

To find a Happy Number we take every digit of a number, square them and add them up. If the sum equals 1 it is a Happy Number. If not we replace the original number by this new sum and repeat the process. If the number repeats then it is not a Happy Number.

Example 1
let n=68
sum of squares =6*6 + 8*8=36 + 64=100
n=100
sum of squares=1*1 + 0*0 + 0*0=1
The sum is 1 therefore 68 is a Happy Number.

Example 2
let n=2
sum of squares=2*2
n=4
sum of squares=4*4
n=16
sum of squares=1*1 + 6*6
n=37
sum of squares=3*3 + 7*7
n=58
sum of squares=5*5 + 8*8
n=89
sum of squares=8*8 + 9*9
n=145
sum of squares=1*1 + 4*4 + 5*5
n=42
sum of squares=4*4 + 2*2
n=20
sum of squares=2*2 + 0*0
n=4.
We get 4 back and therefore this is not a Happy Number.

We need to store all the numbers so that we can compare and see if the number repeats. I have simply appended it to a String and used the indexOf function to check for a repetition.
Here is the complete code

import java.util.Scanner;
public class Happy
{
Scanner sc=new Scanner (System.in);
int m,n;
void accept()
{
m=sc.nextInt();n=sc.nextInt();
}
void allHappy()
{
for(i=m;i<=n;i++)
{
if(isHappy(i))
System.out.print(i + “,”);
}
}
boolean isHappy(int n)
{
String str=”” + n;
while(true)
{
int sum=sumOfSquares(n);
if(sum==1)
return true;
n=sum;
String output=”” + n;
if(str.indexOf(output)>=0)
return false;
str=str + “,” + output;
}
}
int sumOfSquares(int n)
{
int sum=0;
while(n>0)
{
int rem=n % 10;
n=n/10;
sum=sum + rem*rem;
}
return sum;
}
public static void main(String[]args)
{
Happy c=new Happy();
c.accept();
System.out.println(“\nHappy”);
c.allHappy();
}
}

Output

1 100

Happy
1,7,10,13,19,23,28,31,32,44,49,68,70,79,82,86,91,94,97,100

Leave a Reply

Your email address will not be published. Required fields are marked *