![]() |
VOOZH | about |
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:
Below is the implementation of the above approach:
120 180 240
Time Complexity: O(N)
Auxiliary Space: O(1)