Reverse Order – Print multiples of X from N to M
Print all numbers divisible by X in descending order from N to M (inclusive)
Understand the Problem
Problem Statement
Two numbers M and N are passed as the input. A number X is also passed as the input. The program must print the numbers divisible by X from N to M (inclusive of M and N).
Constraints
- 1 <= M <= 9999999
- M < N <= 9999999
- 1 <= X <= 9999
Examples
2
40
735 28 21 14 7From 40 down to 2, the numbers divisible by 7 are 35, 28, 21, 14, and 7. These are printed in descending order.
66
121
11121 110 99 88 77 66From 121 down to 66, the numbers divisible by 11 are 121, 110, 99, 88, 77, and 66. These are printed in descending order.
Solution
#include <stdio.h>
int main() {
int M, N, X;
scanf("%d", &M);
scanf("%d", &N);
scanf("%d", &X);
int found = 0;
// Iterate from N down to M
for (int i = N; i >= M; i--) {
if (i % X == 0) {
if (found) {
printf(" ");
}
printf("%d", i);
found = 1;
}
}
return 0;
}C Solution Explanation:
1. Read input values using scanf for M, N, and X
2. Initialize a flag 'found' to track if we've printed any numbers
3. Loop from N down to M (inclusive) using a for loop
4. For each number, check if it's divisible by X using modulo operator
5. If divisible, print the number with proper spacing (no trailing space)
6. The loop naturally handles the reverse order requirement