Tuesday 27 October 2015

Java Program to check for a Magic Number

A Magic number is a number whose sum of digits eventually leads to 1.
Example#1:  19 ;  1+9 =10 ; 1+0 = 1.  Hence a magic number.
Example#2:  226; 2+2+6=10; 1+0 =1.  Hence a magic number.
Example#3:  874; 8+7+4=19; 1+9=10; 1+0=1.  Hence a magic number.


import java.io.*;
class magicno
{
public static void main(String args[])throws Exception
{
int i,j;
magicno obj=new magicno();             //creating an object for the class to access the function magic.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter a number");
i=Integer.parseInt(br.readLine());   // Accept a number from user to check if it is a magic number or not
while((j=obj.magic(i))/10!=0)       //   You have to check the sum of all digits until a single digit is achieved i.e. sum=1,2,3,..9
{
i=j; // If sum of digits= 19 it then again goes to 1+9 =10 and again 1+0= '1' a single digit to check 1 or not
}
if ( j==1)        // check if the single digit is 1 then a magic number else not
System.out.println("It is a magic number ");
else
System.out.println("Not a magic number");
}
 
int magic(int n)
{
if(n/10==0)
return n;
else
return n%10+ magic(n/10);   // recursive function that gives last digit for every recursion and adds the returned number to previous value.
}
}

No comments:

Post a Comment