Program opened below. You can scroll through the algorithm, Java code and output.
Program 75
Composite Magic Number
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.
Algorithm
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 program
Javaimport 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");
}
}Sample output
Input: 10
Output:
COMPOSITE MAGIC NUMBER