MAGICAL NUMBER

A number is said to be magical, if when we add its digits and repeatedly add the digits of the resulting sum and finally obtain 1.
Example
298 = 2+9+8 = 19
19 = 1+9 = 10
10 = 1+0 =1
Write program to print all magic numbers between a given range.

import java.util.*;
public class Magic
{
    int n1;
    int n2;
    Magic()
    {
    }  
    void input()
        {
            Scanner sc = new Scanner(System.in);
            System.out.println("\nEnter the begin number");
            n1=sc.nextInt();  
            System.out.println("\nEnter the end number");
            n2=sc.nextInt();  
        }
    public int sum(int n)
    {
        int s=0,r;
        while(n>0)
        {
            r=n%10;
            s=s+r;
            n=n/10;
        }
        return s;
    }
    public boolean magic(int n)
    {
        boolean flag=false;
        while(n>9)
        {
            n=sum(n);
        }
        if (n==1)
            flag=true;
        return flag;
    }
  void dispMagic()
    {           
        System.out.println("\nMagic Nos from "+n1 +" and "+n2);;
        for(int i=n1;i<n2;i++)
            if(magic(i))
                System.out.print(i+"\t");
        System.out.println();
                
    }
    public void main()
    {
        Magic A = new Magic();
        A.input();
        A.dispMagic();
    }
This entry was posted in number. Bookmark the permalink.

Leave a Reply

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