A number is said to be magic number if the repetitive sum of digits of number is equal to 1 or a single digit number . If the repetitive sum ends up as 1 then the number is a magic number, else not.
For example-
n= 289;. 2+8+9 = 19
19;. 1+9 = 10
10;. 1+0= 0
1
Since the number ends in 1, hence 289 is a magic number.
Magic number in java is the java program to check whether a number is magic number or not .
For this we do repetitive addition of the digits of the number till the number is a two or more digit number.
If after repetitive adding digits of the number ends up to 1 then the loop stops and a message is displayed.
For this program we need to extract digits of the number for this we use while loop and add this digit .
Code snippet to get digits of the number -
while(n!=0)
{
int d = n%10;
s=s+d;
n=n/10;
}
ALGORITHM-
STEP 1: start STEP 2: print "enter a number" STEP 3: taking input of integer in n STEP 4: repeat STEP 5 to STEP 10 until n>9 STEP 5: int s=0 STEP 6: repeat STEP 7 to STEP 9 until n!=0 STEP 7: int d=n%10 STEP 8: s=s+d STEP 9: n=n/10 STEP 10:n=s STEP 11:if n==1 then goto STEP 12 else goto STEP 13 STEP 12:print "it is a magic number STEP 13:print " it is not a magic number STEP 14:end |
Java code-
import java.util.*;
public class magic
{
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("enter a number");
int n=sc.nextInt();
while(n>9)
{
int s=0;
while(n!=0)
{
int d=n%10;
s=s+d;
n=n/10;
}
n=s;
}
if(n==1)
{
System.out.println("it is a magic number");
}
else
{
System.out.println("it is not a magic number");
}
}
}
Output-
enter a number
289
It is a magic number
similar java codes
if you find helpful please share
Comments
Post a Comment