Computer Science, asked by minuprmundra, 1 year ago

plz send the program code with explanation... plz send properly ​

Attachments:

minuprmundra: plz

Answers

Answered by Anonymous
2

import java.util.*;

class happy_number

{

   public static void main(String args[])

   {

       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");

       }

   }

}

\underline{\mathcal{EXPLANATION}}

The basic logic of a happy number is that the sum of the squares of the digits are counted as long as it is less than ten and then if it is equal to one then the number is a happy number otherwise it is not a happy number .

◼ We start by running two while loops , the first loop contains a swapping and then we initialize the variable "s" to 0 .

◼ Then we normally perform digit extraction by using division . After that we add the squares of the digits which are extracted.

◼ If the variable "s" is less than 9 , then the loop will terminate otherwise we will keep on checking to meet our program requirement .

Similar questions