Question

Check whether a number is Magic number using recursion.

If the sum of its digits recursively are calculated till a single digit. If that single digit is 1 then the number is a magic number.

				
					eg,

28=2+8=10

Adding digits in 28 we get 10,

10=1+0=1

Adding digits in 10 we get 1 

hence, 28 is Magic number
				
			

Share code with your friends

Share on whatsapp
Share on facebook
Share on twitter
Share on telegram

Code

				
					import java.util.Scanner;
public class magicNumber
{
    long num=0,temp=0;
    public void accept()
    {

        Scanner sc=new Scanner(System.in);
        System.out.println("ENTER THE NUMBER");
        num=sc.nextLong();

    }

    public  long CalculateSumOfDigits(long n)
    {

        if(n==0)
        {
            return 0; 
        }
        else
        {
            return n%10 + CalculateSumOfDigits(n/10);   
        }
    }

    public void isMagicNumber()
    {
        temp=num;
        while(temp>9)
        {
            temp=CalculateSumOfDigits(temp);
        }
        if(temp==1)
        {
            System.out.println(num+ " IS A MAGIC NUMBER");   
        }
        else
        {
            System.out.println(num+ " IS NOT A MAGIC NUMBER");   
        }

    }

    public static void main()
    {
        magicNumber ob1=new magicNumber();
        ob1.accept();
        ob1.isMagicNumber();

    }
}
				
			

Coding Store

Leave a Reply

Your email address will not be published. Required fields are marked *