Program opened below. You can scroll through the algorithm, Java code and output.

Composite Magic Number

Download .java

Question

A magic number repeatedly has its digits summed until a single digit remains; if that digit is 1, the number is magic. Accept a positive integer and determine whether it is both composite and magic.

Step 1: Start. Step 2: Declare the variables and data structures required for the task. Step 3: Input N and require N > 1. Step 4: Validate the input values and display an error message if they are outside the permitted range. Step 5: Initialize the counters, flags, accumulators or result structures needed by the solution. Step 6: Count its factors from 1 through N. Step 7: If it has exactly two factors, it is not composite. Step 8: Set temp=N and repeatedly sum its digits until temp is one digit. Step 9: If the final digit is 1 and N is composite, display COMPOSITE MAGIC NUMBER. Step 10: Otherwise display NOT A COMPOSITE MAGIC NUMBER. Step 11: Stop.
Java
import java.util.*;
class CompositeMagic {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        if (n < 2) {
            System.out.println("INVALID INPUT");
            return;
        }
    int factors = 0;
    for (int i = 1; i <= n; i++) {
        if (n % i == 0) {
            factors++;
        }
}
int x = n;
while (x > 9) {
    int sum = 0;
    while (x > 0) {
        sum += x % 10;
        x /= 10;
    }
x = sum;
}
System.out.println(factors > 2 && x == 1 ? "COMPOSITE MAGIC NUMBER" : "NOT A COMPOSITE MAGIC NUMBER");
}
}
Input: 10 Output: COMPOSITE MAGIC NUMBER
← Previous Program 75 of 84 Next →

Share a comment or request a program

Use this form to send a comment, report an issue, or suggest a new practical. Your message will be saved for review by the school.