Question
Print Happy number in an array.
(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.
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
import java.util.Scanner;
public class HappyNumberInArray
{
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)
{
/* Initialize array */
int [] arr;
int n=0,i=0,result=0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number of elements in the array");
n = sc.nextInt();
arr=new int[n];
System.out.println("Enter numbers in array");
for(i=0;i< n;i++)
{
arr[i]=sc.nextInt();
}
/* printing Happy elements in an array */
System.out.println("happy Elements in an array");
for(i=0;i< n;i++)
{
if(arr[i]>0)
{
result = arr[i];
while (result != 1 && result != 4)
{
result = SumOfSquareOfDigits(result);
}
if (result ==1)
{
System.out.println (arr[i]+" ");
}
}
}
}
}