easy
0 views

Print except multiples of N

Print all numbers in a given range [A, B] that are not divisible by a specified number N

Understand the Problem

Problem Statement

Two numbers A and B are passed as input. A number N is also passed as the input. The program must print the numbers from A to B (inclusive of A and B) which are not divisible by N.

Constraints

  • 1 <= A <= 9999999
  • A < B <= 9999999
  • 1 <= N <= 9999
  • All inputs are positive integers

Examples

Example 1
Input
3
20
5
Output
3 4 6 7 8 9 11 12 13 14 16 17 18 19
Explanation

The range is from 3 to 20. The numbers 5, 10, 15, and 20 are divisible by 5, so they are excluded from the output. All other numbers in this range are printed.

Solution

#include <stdio.h>

int main() {
    int A, B, N;
    
    // Read input values
    scanf("%d", &A);
    scanf("%d", &B);
    scanf("%d", &N);
    
    // Iterate through range [A, B]
    for (int i = A; i <= B; i++) {
        // Check if current number is not divisible by N
        if (i % N != 0) {
            printf("%d ", i);
        }
    }
    
    return 0;
}
Time:O(B-A+1) - We iterate through each number in the range [A, B] exactly once
Space:O(1) - Only uses a constant amount of extra space regardless of input size
Approach:

Step-by-step explanation:

  1. Input Reading: Uses scanf() to read three integers A, B, and N from standard input
  2. Loop Structure: A for loop iterates from A to B (inclusive) using variable i
  3. Divisibility Check: For each number i, checks if i % N != 0 (not divisible by N)
  4. Output: If the condition is true, prints the number followed by a space using printf()
  5. Memory Efficiency: Uses only integer variables, O(1) space complexity

The solution efficiently processes each number exactly once, making it optimal for the given constraints.

Visual Explanation

Loading diagram...