medium
0 views

Multiple of N till divisible by X

Find multiples of N starting from N*1 and stop when a multiple is divisible by X

Understand the Problem

Problem Statement

Two numbers N and X are passed as input. The program must print the multiples of N (starting from N*1) and must stop when the multiple is divisible by X.

Constraints

  • 1 <= N <= 9999
  • 1 <= X <= 999999

Examples

Example 1
Input
5
8
Output
5 10 15 20 25 30 35 40
Explanation

Starting with 5, we print multiples: 5, 10, 15, 20, 25, 30, 35, 40. When we reach 40, since 40 % 8 == 0, we stop. The sequence includes all multiples of 5 until we find one divisible by 8.

Example 2
Input
12
22
Output
12 24 36 48 60 72 84 96 108 120 132
Explanation

Starting with 12, we print multiples: 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132. When we reach 132, since 132 % 22 == 0, we stop. The sequence includes all multiples of 12 until we find one divisible by 22.

Solution

#include <stdio.h>

int main() {
    int n, x;
    scanf("%d", &n);
    scanf("%d", &x);
    
    int k = n;
    while (1) {
        if (k % x == 0) {
            printf("%d", k);
            break;
        } else {
            printf("%d ", k);
            k += n;
        }
    }
    
    return 0;
}
Time:O(LCM(N,X)/N) - We iterate through multiples of N until we find one divisible by X
Space:O(1) - Only using constant extra space for variables
Approach:

C Solution Explanation:

  1. Input Reading: Uses scanf to read integers N and X
  2. Initialization: Sets k = n to start with the first multiple
  3. Infinite Loop: Uses while (1) for indefinite iteration
  4. Divisibility Check: If k % x == 0, prints the number without trailing space and breaks
  5. Normal Case: Otherwise prints the number with trailing space and increments k by n
  6. Output Format: Carefully handles spacing - no space after the last number

Visual Explanation

Loading diagram...