Happy Number ISC 2012 Theory

A happy number is a number in which the eventual sum of the square of the digits of the number is equal to 1.

Example 1: 28
22 + 82 = 4 + 64 = 68.
62 + 82 = 36 + 64 = 100.
12 + 02 + 02 = 1.
Hence, 28 is a happy number.

Example 2: 12
12 + 22 = 1 + 4 = 5.
Hence, 12 is not a happy number.

Design a class Happy to check if a given number is a happy number. Some of the members of the class are given below:

Class name: Happy
Data members/instance variables:
n: stores the number.
Member functions:
Happy(): constructor to assign 0 to n.
void getNum(int num): to assign the parameter value num to the number n.
int sumSquareDigits(int x): returns the sum of the squares of the digits of the number x, using the recursive technique.
void isHappy(): checks if the given number is a happy number by calling the function sumSquareDigits(int) and displays an appropriate message.

Specify the class Happy giving details of the constructor, void getNum(int), int sumSquareDigits(int) and void isHappy(). Also define a main() function to create an object and call the methods to check for happy number.

import java.io.*;
class Happy{
    private int n;
    public Happy(){
        n = 0;
    }
    public void getNum(int num){
        n = num;
    }
    public int sumSquareDigits(int x){
        if(x < 10)
            return x * x;
        else{
            int d = x % 10;
            return d * d + sumSquareDigits(x / 10);
        }
    }
    public void isHappy(){
        int sum = n;
        do{
            sum = sumSquareDigits(sum);
        }while(sum > 9);
        if(sum == 1)
            System.out.println(n + " is a happy number.");
        else
            System.out.println(n + " is not a happy number.");
    }
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("N = ");
        int num = Math.abs(Integer.parseInt(br.readLine()));
        Happy obj = new Happy();
        obj.getNum(num);
        obj.isHappy();
    }
}

Leave a Reply