MAGIC NUMBER in MATLAB and JAVA


Write a program to check a number is magic number or not.

A number is said to be a magic number if the eventual sum of digits of the number is one.

Example 1: 
55
Then 5+5=1--1+0=1
Example 2:
289--2+8+9=19--1+9=10--1+0=1
Example 3:
226---2+2+6=10--1+0=1
Example 4:
19--1+9=10---1+0=1
Example 5:
874---8+7+4=19---1+9=10---1+0=1


MATLAB Code:

User defined function:

 function a=myfunction(n)

x=n;
a=0;
while(x>0)
    b=rem(x,10);
    a=a+b;
    x=(x-b)/10;
end
end


Main body:

x=input('Enter the number');
a=x;
while(a>9)
    a=myfunction(a);
end
if(a==1)
    disp('yes');
else
    disp('No');
end


Output:



Explanation:


JAVA CODE:


import java.util.Scanner;

class Magic

{
public static void main(String args[])
{
Scanner obj=new Scanner(System.in);
System.out.println("Enter the number");
int n=obj.nextInt();
int k=n;
while (k>9)
{
k=mac(k);
}
if(k==1)
{
System.out.println("Yes, the number is magic number");
}
else
{
System.out.println("No, the number is not magic number");
}

}
public static int mac(int x)
{
int b=0;
int rs=0;
while(x>0)
{
b=x%10;
rs=rs+b;
x=x/10;
}
return(rs);
}
}


Output:


Reference video:




No comments