Program to check for Happy Number
=========================================================================
If a number is happy, then all members of its
sequence are happy; if a number is unhappy, all members of the sequence are
unhappy.
For example, 19 is happy, as the associated
sequence is:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 =
1.
The 143 happy numbers up to 1,000 are:
1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70,
79, 82, 86, 91, 94, 97, 100, 103, 109, 129, 130, 133, 139, 167, 176, 188, 190,
192, 193, 203, 208, 219, 226, 230, 236, 239, 262, 263, 280, 291, 293, 301, 302,
310, 313, 319, 320, 326, 329, 331, 338, 356, 362, 365, 367, 368, 376, 379, 383,
386, 391, 392, 397, 404, 409, 440, 446, 464, 469, 478, 487, 490, 496, 536, 556,
563, 565, 566, 608, 617, 622, 623, 632, 635, 637, 638, 644, 649, 653, 655, 656,
665, 671, 673, 680, 683, 694, 700, 709, 716, 736, 739, 748, 761, 763, 784, 790,
793, 802, 806, 818, 820, 833, 836, 847, 860, 863, 874, 881, 888, 899, 901, 904,
907, 910, 912, 913, 921, 923, 931, 932, 937, 940, 946, 964, 970, 973, 989, 998,
1000.
The happiness of a number is unaffected by
rearranging the digits, and by inserting or removing any number of zeros
anywhere in the number.
The program to check if a number is Happy or not is
given below : -
-------------------------------------------------------------------------------------------------------------
import java.util.Scanner;
class Happy
{
Scanner S = new Scanner(System.in);
int no;
public boolean isHappy(int x)
{
int y = x;
int sum =
sumofdigitsquare(y);
int u=0;
while(sum>9)
sum =
sumofdigitsquare(sum);
if(sum==1)
return true;
else
return false;
}
public int sumofdigitsquare(int x)
{
int sum = 0;
while(x>0)
{
sum = sum
+((x%10)*(x%10));
x=x/10;
}
return sum;
}
public void main()
{
System.out.println("Enter the number to be checked for Happy :-");
if(isHappy(S.nextInt()))
System.out.println("It is a Happy Number");
else
System.out.println("Tis not a Happy Number");
}
}
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
For other Number checking programs, check my other
blog...<Click Here>
No comments:
Post a Comment