SPY Number in MATLAB
A number is a Spy number, if sum and product of all digits are equal. Example: Number 123 is a Spy number, sum of its digits is 6 (1+2+3 =6) and product of its digits is 6 (1*2*3 = 6), sum and product are same, thus, 123 is a spy number.
Algorithm:
1) Extract the digits.
You can use the following rule:
x=input('Enter the number');
m=x;
while(m>0)
b=rem(m,10);
%This line has to be written according to the requirement.
m=(m-b)/10;
end
For detail explanation , you can check this video:
2) Multiply those digits.
3) Add all the digits .
4) Check whether they are equal or not using if else condition.
Code to check whether a number is SPY number or not:
x=input('Enter the number');
m=x;
t=0;
p=1;
while (m>0)
b=rem(m,10);
t=t+b;
p=p*b;
m=(m-b)/10;
end
if(t==p)
disp('Yes , this is a SPY number');
else
disp('No , not a SPY number');
end
Explanation of the code:
Code to print all the SPY numbers between 1 and user input number:
g=input('Enter the number');
Y=[];
for x=1:g
m=x;
t=0;
p=1;
while (m>0)
b=rem(m,10);
t=t+b;
p=p*b;
m=(m-b)/10;
end
if(t==p)
Y=[Y x];
end
end
For java / C/ C++ code , you can check the following link:
No comments