Tuesday, 27 October 2015

Java program to print the magic number series

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:  224; 2+2+4=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 magic
{
public static void main(String args[])throws Exception
{
int i,j,k,n;
magic obj=new magic();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("enter the upper limit to print the magic number series: ");  // i.e the value of n;
n=Integer.parseInt(br.readLine());
for(k=0;k<n;k++)
{i=k;
while((j=obj.magicno(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 if 1 or not
}
if ( j==1)
System.out.print(k+",");
}
}
 
int magicno(int n)     // recursive program for magic number
{
if(n/10==0)
return n;
else
return n%10 + magicno(n/10);
}
}

No comments:

Post a Comment