Java Program to Check for Magic Numbers

Answered using GPT-4o-mini by Java Q&A Hub

Question:

Write a Java Program to check if any number is a magic number or not. A number is said to be a magic number if after doing the sum of digits in each step and in turn doing the sum of digits of that sum, the ultimate result (when there is only one digit left) is 1.

Answer:

A magic number is defined as a number that ultimately reduces to 1 when you repeatedly sum its digits until only one digit remains. This can be achieved using a simple Java program. Below is a Java program that checks if a given number is a magic number or not.

import java.util.Scanner;

public class MagicNumberChecker {

    // Function to calculate the sum of digits of a number
    public static int sumOfDigits(int number) {
        int sum = 0;
        while (number > 0) {
            sum += number % 10; // Add the last digit to sum
            number /= 10;       // Remove the last digit
        }
        return sum;
    }

    // Function to check if a number is a magic number
    public static boolean isMagicNumber(int number) {
        // Continue summing the digits until we have a single digit
        while (number >= 10) {
            number = sumOfDigits(number);
        }
        // Check if the final single digit is 1
        return number == 1;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int number = scanner.nextInt();

        if (isMagicNumber(number)) {
            System.out.println(number + " is a magic number.");
        } else {
            System.out.println(number + " is not a magic number.");
        }

        scanner.close();
    }
}

Explanation of the Code:

  1. sumOfDigits Method: This method takes an integer as input and returns the sum of its digits. It uses a while loop to extract each digit and add it to the sum.

  2. isMagicNumber Method: This method checks if the given number is a magic number. It repeatedly calls the sumOfDigits method until the number is reduced to a single digit. Finally, it checks if that single digit is 1.

  3. Main Method: This is the entry point of the program. It prompts the user to enter a number, checks if it is a magic number using the isMagicNumber method, and prints the result.

How to Run the Program:

  1. Copy the code into a file named MagicNumberChecker.java.
  2. Compile the program using javac MagicNumberChecker.java.
  3. Run the program using java MagicNumberChecker.
  4. Enter a number when prompted to check if it is a magic number.