write a program to check magic number or not
Answers
program in
PYTHON3 :
def isMagic(n):
sum = 0;
# Note that the loop
# continues if n is 0
# and sum is non-zero.
# It stops when n becomes
# 0 and sum becomes single
# digit.
while (n > 0 or sum > 9):
if (n == 0):
n = sum;
sum = 0;
sum = sum + n % 10;
n = int(n / 10);
# Return true if sum becomes 1.
return True if (sum == 1) else False;
# Driver code
n = 1234;
if (isMagic(n)):
print("Magic Number");
else:
print("Not a magic Number");
Check if it runs properly ;-)
Answer:
import java.util.*;
class magic_number
{
public void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number to check whether it is a magic number or not");
int n=sc.nextInt();
int d=0;
int s=n;
while(s>9)
{
n=s;
s=0;
while(n>0)
{
d=n%10;
s=s+d;
n=n/10;
}
}
if(s==1)
{
System.out.println("Magic number");
}
else
{
System.out.println("Not a magic number");
}
}
}
Explanation:
We can check magic number by running two while loops .
Note that we have to swap the values of 's' and 'n' .
Then if s<9 loop ends .