Happy number in java

Happy number in java

Happy number in java

Any positive natural integer number square of its digit and sum it up and repeat the sequence until reach in single digit. If the single digit is 1 and then it is a happy number otherwise not a happy number.

Example

28

2x2 + 8x8 = 4 + 64 = 68

6x6 + 8x8 = 36 + 64 = 100

1x1 + 0x0 + 0x0 = 1 + 0 + 0 = 1

In the following program a number is input from the main() method and that number is pass to the isHappyNumber(int number) method where it will  sum the square of its digit and then again do the same until the sum come’s in single digit. That digit return to the main() method and check the number, if it is 1 the it is called Happy Number else not a Happy number.

import java.util.Scanner;

public class HappyNumberinJava 

{    

    int reminder, sum, num ;  // Instance Variable

    // Constructor

    public HappyNumberinJava()

    {

        sum = 0;

        num = 0;

    }

    public int isHappyNumber(int number)

    { 

        num = number;   

        while (num > 9)

        {

            while (num > 0)

            {

                reminder = num % 10;

                sum = sum + (reminder * reminder);

                num = num / 10;

            }

            num = sum;

            sum = 0;

        }

        return num; 

    } 

    // main() method 

    public static void main(String[] args)

    {  

        int n; // Take the number

        int rnumber; // value from the function

        HappyNumberinJava ob = new HappyNumberinJava(); // object

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter a number to check happy number :");

        n = sc.nextInt();

        rnumber = ob.isHappyNumber(n);

        if(rnumber == 1)

        {

            System.out.println("Happy number");

        }

        else

        {

            System.out.println("Not a happy number");

        }           

    } 

Java program


 


SHARE THIS
Previous Post
Next Post