PROGRAM : MAGICAL NUMBER BY RECURSION
This program checks if a number is a Magic number in JAVA. A number is said to be a Magic number if the sum of its digits are calculated till a single digit is obtained by recursively adding the sum of its digits. If the single digit comes to be 1 then the number is a magic number.Example: 10999 => 1+0+9+9+9=28=>2+8=>10=>1+0=1
199 =>1+9+9 =>19=> 1+9=>10=>1+0=1
SYNTAX
import java.io.*;class magic
{ static int c;
public static void main(String arsg[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n;int d=0;int m;
System.out.println("ENter a NUmber");
n=Integer.parseInt(br.readLine());
m=n;
while(n!=0)
{d=n%10;
n=n/10;
c++;
}
magical(m);
}
public static void magical(int x)
{ int i=0,d=0,sum=0;
for(i=0;i<c;i++)
{
d=x%10;
sum+=d;
x=x/10;
}
if(sum>9){
magical(sum);}
else
val(sum);
}
public static void val(int a)
{
if(a==1)
System.out.println("YES THE NUMBER IS MAGICAL NUMBER");
else
System.out.println("NO THE NUMBER IS NOT MAGICAL");
}
}
Appropriate...thanks
ReplyDeletethanks a lot
ReplyDeleteThe definition of magic number is wrong
ReplyDelete