Home / Blue J / Java Program to check for a Magic Number

Java Program to check for a Magic Number

This is a Java program for Magic number. However before starting let me tell you what is 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.

ALSO CHECK: Java program to print the magic number series

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.
}
}

OUTPUT:

java program for magic number
java program for magic number
 java program for magic number

Check Also

Program to check Upper Triangular matrix

What is Upper Triangular Matrix?  An upper triangular matrix is a square matrix in which ...

2 comments

  1. It was very helpful.

  2. It was very helpful

Leave a Reply

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

Preventing spam * Time limit is exhausted. Please reload the CAPTCHA.