Question

Print Magic number in given range 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 of 28 we get 10,

10=1+0=1

Adding digits of 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 lowerRange=0,upperRange=0,temp=0,i=0;
    public void accept()
    {

        Scanner sc=new Scanner(System.in);
        System.out.println("ENTER THE LOWER NUMBER");
        lowerRange=sc.nextLong();
        System.out.println("ENTER THE UPPER NUMBER");
        upperRange=sc.nextLong();

    }

    public  long CalculateSumOfDigits(long n)
    {

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

    public void isMagicNumber()
    {
        System.out.println("MAGIC NUMBER(S) BETWEEN "+lowerRange +" AND "+upperRange+":");
        for(i=lowerRange;i<=upperRange;i++)
        {
            temp=i;
            while(temp>9)
            {
                temp=CalculateSumOfDigits(temp);
            }
            if(temp==1)
            {
                System.out.print(i+ " ");   
            }  
        }


    }

    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 *