Program opened below. You can scroll through the algorithm, Java code and output.
Program 26
Composite Magic Numbers in a Range
Question
Accept two positive limits and display all numbers that are both composite and magic (their repeated digit sum is 1).
Algorithm
Step 1: Start and read both limits.
Step 2: Validate that the range is positive and ordered.
Step 3: Define a composite-number checking function.
Step 4: Return false for values smaller than four.
Step 5: Search for a divisor between two and the square root.
Step 6: Return true if a proper divisor is found.
Step 7: Define a function that checks whether a number is magic.
Step 8: Repeatedly add decimal digits when the value contains more than one digit.
Step 9: Replace the value with the newly computed sum.
Step 10: Repeat until one digit remains.
Step 11: Return true only when that remaining digit is one.
Step 12: Start a loop from the lower to the upper limit.
Step 13: Test each value using both helper functions.
Step 14: Display the value only when both conditions are satisfied.
Step 15: Stop.
Java program
Javaimport java.util.*;
class CompositeMagic {
static boolean composite(int n) {
if (n < 4) {
return false;
}
for (int i = 2; i <= n / i; i++) {
if (n % i == 0) {
return true;
}
}
return false;
}
static boolean magic(int n) {
while (n > 9) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
n = sum;
}
return n == 1;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
if (a < 1 || b < a) {
System.out.println("Invalid range");
return;
}
for (int n = a; n <= b; n++) {
if (composite(n) && magic(n)) {
System.out.println(n);
}
}
}
}Sample output
Input: 10 40
Output: 10 28