Happy Number ISC Computer Science 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:
Consider the number 28.
22 + 82 = 4 + 64 = 68
62 + 82 = 36 + 64 = 100
12 + 02 + 02 = 1.
Hence, 28 is a happy number.
Now consider the number 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 to the number n = num.
int sumSquareDigits(int x): returns the sum of the square 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 functions. Also define main() function to create an object and call the methods to check for happy number.

import java.util.Scanner;
class Happy{
    int n;
    public Happy(){
        n = 0;
    }
    public void getNum(int num){
        n = num;
    }
    public int sumSquareDigits(int x){
        if(x < 10)
            return x;
        return x % 10 + sumSquareDigits(x / 10);
    }
    public void isHappy(){
        int result = n;
        do{
            result = sumSquareDigits(result);
        }while(result > 9);
        if(result == 1)
            System.out.println("Happy number!");
        else
            System.out.println("Not a happy number.");
    }
    public static void main(String args[]){
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the number: ");
        int num = Integer.parseInt(in.nextLine());
        Happy obj = new Happy();
        obj.getNum(num);
        obj.isHappy();
    }
}

Comments

Popular posts from this blog

Encrypt Program ISC Specimen 2023 Theory

No Repeat Program ISC Computer Science 2022 Semester 2 Theory

Bank Inheritance Program ISC Specimen 2023 Theory