Computer Science, asked by Adritachatterji, 1 year ago

Write a program in java to check whether a number is a happy number or not? (class 9)

Answers

Answered by Rulebreaker22
2
using import package I have taken
Attachments:
Answered by Anonymous
4

Answer:

import java.util.*;

class happy_number

{

   public void main()

   {

       Scanner sc=new Scanner(System.in);

       System.out.println("Enter a number to check whether it is a magic number or not");

       int n=sc.nextInt();

       int d=0;

       int s=n;

       while(s>9)

       {

           n=s;

           s=0;

           while(n>0)

           {

               d=n%10;

               s=s+(d*d);

               n=n/10;

           }

       }

       if(s==1)

       {

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

       }

       else

       {

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

       }

   }

}  

Explanation:

A number is called happy number if the sum of square of its digits until less than 10 are added up to get one as the final result .

Example is :

31

3² + 1² = 9 + 1 = 10

1² + 0² = 1 + 0 = 1

1 is the final result .

Hence 31 is happy .

Similar questions