Java Program to Check a number is Magic Number or Not


In mathematics, if the sum of its digits recursively is calculated till a single digit. If the single digit is 1 then the number is called a magic number. It is quite similar to the happy number.

For example, 325 is a magic number because the sum of its digits (3+2+5) is 10, and again sum up the resultant (1+0), we get a single digit (1) as the result. Hence, the number 325 is a magic number.


 Code:
import java.util.Scanner;  
public class CheckMagicNumber 
{  
    public static void main(String args[])  
    {  
        int n, remainder = 1, number, sum = 0;  
        //creating a constructor of the Scanner class  
        Scanner sc = new Scanner(System.in);  
        System.out.print("Enter a number you want to check: ");  
        //reading an integer form the user  
        n = sc.nextInt();  
        //assigning the entered number in the variable num  
        number = n;  
        //outer while loop  
        while (number > 9)    //while(number > 0 || sum > 9)  
        {  
            //inner while loop      
            while (number > 0)  
            {  
            //determines the remainder      
            remainder = number % 10;   
            sum = sum + remainder;  
            //divides the number by 10 and removes the last digit of the number  
            number = number / 10;     
            }  
            number = sum;  
            sum = 0;  
        }  
        if (number == 1)  
        {  
        System.out.println("The given number is a magic number.");  
        }  
        else  
        {  
        System.out.println("The given number is not a magic number.");  
        }  
    }  
}  

Output:








AJ Blogs

Hello everyone, My name Arth and I like to write about what I learn. Follow My Website - https://sites.google.com/view/aj-blogs/home

Post a Comment

Previous Post Next Post
Best Programming Books

Facebook

AJ Facebook
Checkout Our Facebook Page
AJ Blogs
Checkout Our Instagram Page