Magic Number Program in Java

A magic number is a number that possesses unique properties and can be calculated using a specific mathematical formula. When a number is considered to be a magic number, it has a special quality that sets it apart from other numbers.

To calculate a magic number, the digits of the number are added together repeatedly until a single digit(1) is obtained. This single digit(1) is then considered the magic number. For example, the number 1234 would be calculated as follows: 1 + 2 + 3 + 4 = 10, and 1 + 0 = 1. Therefore, 1234 is a magic number.

import java.util.Scanner;

public class MagicNumber
{
    public static void main(String[] args)
    {
        int n, r = 1, num, sum = 0;
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter number=");
        n = sc.nextInt();
        num = n;
        while (num > 9)
        {
            while (num > 0)
            {
                r = num % 10;
                sum = sum + r;
                num = num / 10;
            }
            num = sum;
            sum = 0;
        }
        if (num == 1)
        {
            System.out.println("Magic Number");
        }
        else
        {
            System.out.println("Not Magic Number");
        }
    }
}

Input: The program prompts the user to enter a number using the line System.out.print("Enter number="). The user is expected to enter an integer value and press enter.

Output: The program checks if the entered number is a magic number or not using the given formula to calculate the magic number. If the entered number is a magic number, it outputs “Magic Number”. If it’s not a magic number, it outputs “Not Magic Number”.

For example, let’s say the user enters the number 1234. The program calculates the sum of the digits of 1234 as 1+2+3+4=10. Since the sum is greater than 9, the program continues to calculate the sum of the digits of 10 as 1+0=1. Since the resulting number is 1, the program outputs “Magic Number”.

On the other hand, if the user enters the number 123, the program calculates the sum of the digits of 123 as 1+2+3=6. Since the resulting number is not 1, the program outputs “Not Magic Number”.

Leave a Comment