MAGIC NUMBER:
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:
199 is a magic number as 1+9+9=19 but 19 is not a single digit number so 1+9=10 and then 1+0=1 which is a single digit number and also 1.Hence it is a magic number.
/*Java program to check given number is magic number or not*/
import java.util.*;
public class MagicNumber
{
public static void main(String args[])
{
Scanner ob=new Scanner(System.in);
System.out.println("Enter the number:");
int n=ob.nextInt();
int sum=0,num=n;
while(num>9)
{
sum=num;int s=0;
while(sum!=0)
{
s=s+(sum%10);
sum=sum/10;
}
num=s;
}
if(num==1)
{
System.out.println(n+" is a Magic Number.");
}
else
{
System.out.println(n+" is not a Magic Number.");
}
}
}
OUTPUT:
Enter the number:
12
12 is not a Magic Number.
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:
199 is a magic number as 1+9+9=19 but 19 is not a single digit number so 1+9=10 and then 1+0=1 which is a single digit number and also 1.Hence it is a magic number.
/*Java program to check given number is magic number or not*/
import java.util.*;
public class MagicNumber
{
public static void main(String args[])
{
Scanner ob=new Scanner(System.in);
System.out.println("Enter the number:");
int n=ob.nextInt();
int sum=0,num=n;
while(num>9)
{
sum=num;int s=0;
while(sum!=0)
{
s=s+(sum%10);
sum=sum/10;
}
num=s;
}
if(num==1)
{
System.out.println(n+" is a Magic Number.");
}
else
{
System.out.println(n+" is not a Magic Number.");
}
}
}
OUTPUT:
Enter the number:
12
12 is not a Magic Number.
Enter the number:
19
19 is a Magic Number.
Could you explain the working in the while block
ReplyDeleteDo yourself
DeleteIs 8794 a magic number
ReplyDeleteThis comment has been removed by the author.
DeleteYes
DeleteYes
DeleteYes it is a magic number.
ReplyDelete8 + 7 + 9 + 4 = 28;
Delete2 + 8 = 10;
1 + 0 = 1;
Therefore it is a magic number.
Could not understand
ReplyDelete7+8+3+4+9+6=37;
ReplyDelete3+7=10;
1+0=1;
yes,it is a magic number
Wrong program, it will add the digits of the number only once whereas according to magic number definition we must add the digits untill it becomes a single digit number, after that we will check if it's 1 or not.
ReplyDeleteI have doubt in the given output... The output is 12 and hence when we will add the digits i.e 1+2=3 ..so therefore it is a single digit number na.. So how it is not a magic number???????
ReplyDelete