VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-numbers-in-between-l-r-which-are-divisible-by-all-array-elements/

⇱ Find numbers in between [L, R] which are divisible by all Array elements - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find numbers in between [L, R] which are divisible by all Array elements

Last Updated : 23 Jul, 2025

Given an array arr[] containing N positive integers and two variables L and R indicating a range of integers from L to R (inclusive). The task is to print all the numbers between L to R which are divisible by all array elements. If no such value exists print -1.

Input: arr[] = {3, 5, 12}, L = 90, R = 280
Output: 120 180 240 
Explanation: 120, 180, 240 are the numbers which are divisible by all the arr[] elements.

Input: arr[] = {4, 7, 13, 16}, L = 200, R = 600
Output: -1

Naive Approach: In this approach for every element in range [L, R] check if it is divisible by all the elements of the array.

Time Complexity: O((R-L)*N)
Auxiliary Space: O(1)

Efficient Approach: The given problem can be solved using basic math. Any element divisible by all the elements of the array is a multiple of the LCM of all the array elements. Find the multiples of LCM in the range [L, R] and store in an array. At last print the numbers stored in the array.

Time Complexity: O(N)
Auxiliary Space: O(R - L)

Space Optimized Approach: Below steps can be used to solve the problem:

  1. Calculate the LCM of all the elements of given arr[]
  2. Now, check the LCM for these conditions:
    1. If (LCM < L and LCM*2 > R), then print -1.
    2. If (LCM > R), then print -1.
  3. Now, take the nearest value of L (between L to R) which is divisible by the LCM, say i.
  4. Now, start printing i and increment it by LCM every time after printing, until it becomes greater than R.

Below is the implementation of the above approach: 


Output
120 180 240 

Time Complexity: O(N)
Auxiliary Space: O(1)


 

Comment