Computer Applications
A happy number is a number which eventually reaches 1 when replaced by the sum of the square of each digit. For example, consider the number 320.
32 + 22 + 02 ⇒ 9 + 4 + 0 = 13
12 + 32 ⇒ 1 + 9 = 10
12 + 02 ⇒ 1 + 0 = 1
Hence, 320 is a Happy Number.
Write a program in Java to enter a number and check if it is a Happy Number or not.
Answer
import java.util.Scanner;
public class KboatHappyNumber
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number to check: ");
long num = in.nextLong();
long sum = 0;
long n = num;
do {
sum = 0;
while (n != 0) {
int d = (int)(n % 10);
sum += d * d;
n /= 10;
}
n = sum;
} while (sum > 6);
if (sum == 1) {
System.out.println(num + " is a Happy Number");
}
else {
System.out.println(num + " is not a Happy Number");
}
}
}Output
Related Questions
To execute a loop 10 times, which of the following is correct?
- for (int i=11;i<=30;i+=2)
- for (int i=11;i<=30;i+=3)
- for (int i=11;i<20;i++)
- for (int i=11;i<=21;i++)
Define a class to accept a number from user and check if it is an EvenPal number or not.
(The number is said to be EvenPal number when number is palindrome number (a number is palindrome if it is equal to its reverse) and sum of its digits is an even number.)
Example: 121 – is a palindrome number
Sum of the digits – 1+2+1 = 4 which is an even number