Magic Number in JAVA

Magic Number in JAVA


A Number is said to be a Magic Number if the sum of its digits are calculated till a single digit is obtained by recursively adding the sum of its digits.
If the single digit comes to be 1 then the number is a Magic Number.

Example- 199 is a magic number as 1+9+9=19 but 19 is not a sigle digit number so 1+9=10 and then 1+0=1 which is a single digit number and also 1.Hence it is a magic number.

PROGRAM below :-

import java.io.*;
import java.util.*;
class Magic
{
    public static void main(String args[])
    {
        Scanner in= new Scanner(System.in);
        int n,p,x=0;
        System.out.println("Enter Number");
        n= in.nextInt(); // Input number from user
        p=n; // store the entered number in "p" variable
        while(n>9)
        {
            int s=0;
            x=n;
            while(x!=0)
            {
                s=s+(x%10);
                x=x/10;
            }
            n=s;
        }
        if(n==1) // if final digit is 1
        {
            System.out.println("It is Magic Number : "+p);
        }
        else
        {
            System.out.println("It is not Magic Number : "+p);
        }
    } // end of main method
} // end of class



Comment if algorithm needed.

Comments

Post a Comment

Popular posts from this blog

Frequency of each digit of a number in Java

Trimorphic Number in JAVA

PalPrime Number in JAVA