Explanation :
If n=1729 then find the sum of digits of the given number i.e,
(1 + 7 + 2 + 9 =19). Reverse of 19 is 91.
Then (19 X 91 = 1729).
If the obtained product value and the given input are same, then the given number is a magic number.
Code:
import java.util.Scanner;public class MagicNumber
{
public static void main (String args[])
{
int num, sum, rev;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the value for num:");
num=sc.nextInt();
MagicNumber m=new MagicNumber();
sum = m.sumOfDigits(num);
rev = m.reverse(sum);
if (sum < 10)
{
if ((sum * sum) == num)
{
System.out.println(num+" is a magic number");
}
else
{
System.out.println(num+" is not a magic number");
}
}
else if ((sum * rev) == num)
{
System.out.println(num+" is a magic number");
}
else
{
System.out.println(num+" is not a magic number");
}
sc.close();
}
public int sumOfDigits(int n)
{
int s = 0;
while (n > 0)
{
s = s + (n % 10);
n = n / 10;
}
return s;
}
public int reverse(int num)
{
int rev = 0;
while (num > 0)
{
rev = (rev * 10) + (num % 10);
num = num / 10;
}
return rev;
}
}
No comments:
Post a Comment