Open In App

Find Kth smallest number among multiples of all elements of array

Last Updated : 18 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Consider an array arr[] of size N consisting of prime numbers and an integer K. The task is to find the Kth smallest number among the multiples of all elements of the array.

Constraints:

1 <= N <= 10
1 < arr[i] < 30
1<=K<=1e12

Examples:

Input: N = 3, arr[] = {3, 5, 7}, K=5
Output: 9
Explanation:

  • arr[0] has multiples 3, 6, 9, 12, 15… so on.
  • arr[1] has multiples 5, 10, 15, 20, 25… so on.
  • arr[2] has multiples 7, 14, 21, 28, 35… so on.

If we arrange all the multiples in ascending order, then we’ll get: 3, 5, 6, 7, 9, 10, 12… so on. Among all these multiples, the 5th smallest multiple is 9.

Input: N = 2, arr[] = {7, 11}, K = 3
Output: 14
Explanation:

  • arr[0] has mutiples 7, 14, 21, 28… so on.
  • arr[1] has multiples 11, 22, 33, 44… so on.

If we arrange all the multiples in ascending order, then we’ll get 7, 11, 14, 21, 22, 28… so on. Among all these multiples, the 3rd smallest multiple is 14.

Naive Approach:

Initially we will be having a count of numbers (cnt) initialized to zero, we will be start iterating from 2 and for each integer we will check if it is divisible by any of the numbers in the array, if it is then the count(cnt) will be incremented by 1. When the value of count is equal to K then we will break the loop and returning the answer.

C++
#include <bits/stdc++.h>
using namespace std;

long long int solve(vector<int>& arr, long long int& K)
{
    // initialise the count (cnt) = 0
    long long int cnt = 0;
    long long int i = 2;
    while (cnt < K) {
        for (int j = 0; j < arr.size(); j++) {
            if (i % arr[j] == 0) {
                cnt++;
                if (cnt == K) {
                    return i;
                    break;
                }
            }
        }
        i++;
    }
    return 0;
}

int main()
{
    long long int K = 5;
    vector<int> arr = { 3, 5, 7 };
    cout << solve(arr, K) << endl;
    return 0;
}
Java
import java.util.ArrayList;

public class Main {

    static long solve(ArrayList<Integer> arr, long K)
    {
        // initialize the count (cnt) = 0
        long cnt = 0;
        long i = 2;

        while (cnt < K) {
            for (int j = 0; j < arr.size(); j++) {
                if (i % arr.get(j) == 0) {
                    cnt++;
                    if (cnt == K) {
                        return i;
                    }
                }
            }
            i++;
        }
        return 0;
    }

    public static void main(String[] args)
    {
        long K = 5;
        ArrayList<Integer> arr = new ArrayList<>();
        arr.add(3);
        arr.add(5);
        arr.add(7);

        System.out.println(solve(arr, K));
    }
}

// This code is contributed by shivamgupta0987654321
Python3
# Python Implementation


def solve(arr, K):
    # initialise the count (cnt) = 0
    cnt = 0
    i = 2
    while cnt < K:
        for j in range(len(arr)):
            if i % arr[j] == 0:
                cnt += 1
                if cnt == K:
                    return i
                    break
        i += 1
    return 0


if __name__ == "__main__":
    K = 5
    arr = [3, 5, 7]
    print(solve(arr, K))


# This code is contributed by Tapesh(tapeshdu420)
C#
using System;
using System.Collections.Generic;

public class GFG {
    static long Solve(List<int> arr, long K)
    {
        // initialize the count (cnt) = 0
        long cnt = 0;
        long i = 2;

        while (cnt < K) {
            foreach(int num in arr)
            {
                if (i % num == 0) {
                    cnt++;
                    if (cnt == K) {
                        return i;
                    }
                }
            }
            i++;
        }
        return 0;
    }

    public static void Main(string[] args)
    {
        long K = 5;
        List<int> arr = new List<int>();
        arr.Add(3);
        arr.Add(5);
        arr.Add(7);

        Console.WriteLine(Solve(arr, K));
    }
}
JavaScript
// Javascript program for the above approach

// Function to find the Kth number that is divisible by any number in the given array
function solve(arr, K) {
    let cnt = 0; // Initialize count of divisible numbers found
    let i = 2; // Start checking from number 2 (since 1 is divisible by all numbers)
    while (cnt < K) { // Continue until K divisible numbers are found
        for (let j = 0; j < arr.length; j++) { // Iterate over each number in the array
            if (i % arr[j] === 0) { // Check if the current number is divisible by any number in the array
                cnt++; // Increment count if divisible
                if (cnt === K) { // If K divisible numbers are found, return the current number
                    return i;
                }
            }
        }
        i++; // Move to the next number to check
    }
    return 0; // If K divisible numbers are not found, return 0
}

const K = 5; // Define the value of K
const arr = [3, 5, 7]; // Define the array of numbers to check for divisibility
console.log(solve(arr, K)); // Call the solve function with the given parameters and print the result

// This code is contributed by Susobhan Akhuli

Output
9

Time Complexity: O(N * K)
Auxiliary Space: O(1).

Find Kth smallest number among multiples of all elements of array using Binary Search:

The problem can be solved using Binary Search on the search space [0, 1e18]. Find the mid and count how many multiples are there less than or equal to mid. If the count of multiples < K then it means that the answer > mid, so we shift lo = mid + 1 otherwise if count of multiples >= K, then it means that answer <= mid, so we update the result and shift hi = mid – 1.

The count of multiples less than or equal to mid can be calculated as follows:

If there are only 3 elements in the arr[] = {p1, p2, p3} then we can count elements below mid as

COUNT = X/p1 + X/p2 + X/p3 – X/(p1*p2) – X/(p1*p3) – X/(p2*p3) + X(p1*p2*p3), here

  • X/p1 is number of multiples of p1 till X,
  • X/p2 is number of multiples of p2 till X,
  • X/p3 is number of multiples of p3 till X,
  • X/(p1*p2) is the number of common multiples of p1 and p2 these have to subtracted once as they been counted twice,
  • X/(p2*p3) is the number of common multiples of p2 and p3 these have to subtracted once as they been counted twice,
  • X/(p3*p1) is the number of common multiples of p1 and p3 these have to subtracted once as they been counted twice,
  • As the numbers having p1, p2, p3 as factors will be subtracted thrice, they must be added once to suffice the equation.

This formula can be generalized for N primes in an array.

Step-by-step algorithm:

  • Initialize two variables lo = 0 and hi = 1e18, as lower and upper bounds of binary search.
  • Calculate the mid and count how many multiples are less than or equal to mid using the check function.
  • If count of multiples is greater than or equal to K, then the res is assigned with mid and right search space is reduced (hi = mid -1).
  • And if the count of numbers is less than K, the left search space is reduced (lo = mid +1).
  • Keep on reducing the search space till we get the final answer.

Below is implementation of the algorithm:

C++
#include <iostream>
#include <vector>
using namespace std;

// Function to check if mid >= Kth smallest multiple
bool check(long long mid, vector<int>& arr, long long N,
           long long K)
{
    // Variable to store the count of multiples till K
    long long count = 0;

    for (int i = 1; i < (1 << N); i++) {
        long long product = 1;
        bool sign = true;
        for (int j = 0; j < N; j++) {
            if (i & (1 << j)) {
                product = product * arr[j];
                sign = !sign;
            }
        }
        if (sign) {
            count -= mid / product;
        }
        else {
            count += mid / product;
        }
    }
    return count >= K;
}

// Function to find the Kth smallest multiple
long long solve(vector<int>& arr, long long K)
{
    long long low = 0, hi = 1e18;
    long long N = arr.size();
    long long res = 0;

    while (low <= hi) {
        long long mid = low + (hi - low) / 2;
        if (check(mid, arr, N, K)) {
            res = mid;
            hi = mid - 1;
        }
        else {
            low = mid + 1;
        }
    }
    return res;
}

int main()
{
    int k = 5;
    vector<int> arr = { 3, 5, 7 };
    cout << "The 5th number to be selected on the number "
            "line is: "
         << solve(arr, k) << endl;
    return 0;
}
Java
// Java program for the above approach
import java.util.*;

public class GFG {
    // Function to check if mid >= Kth smallest multiple
    static boolean check(long mid, ArrayList<Integer> arr,
                         long N, long K)
    {
        // Variable to store the count of multiples till K
        long count = 0;

        for (int i = 1; i < (1 << N); i++) {
            long product = 1;
            boolean sign = true;
            for (int j = 0; j < N; j++) {
                if ((i & (1 << j)) != 0) {
                    product = product * arr.get(j);
                    sign = !sign;
                }
            }
            if (sign) {
                count -= mid / product;
            }
            else {
                count += mid / product;
            }
        }
        return count >= K;
    }

    // Function to find the Kth smallest multiple
    static long solve(ArrayList<Integer> arr, long K)
    {
        long low = 0, hi = (long)1e18;
        long N = arr.size();
        long res = 0;

        while (low <= hi) {
            long mid = low + (hi - low) / 2;
            if (check(mid, arr, N, K)) {
                res = mid;
                hi = mid - 1;
            }
            else {
                low = mid + 1;
            }
        }
        return res;
    }

    public static void main(String[] args)
    {
        int k = 5;
        ArrayList<Integer> arr
            = new ArrayList<>(Arrays.asList(3, 5, 7));
        System.out.println(
            "The 5th number to be selected on the number line is: "
            + solve(arr, k));
    }
}

// This code is contributed by Susobhan Akhuli
Python3
# Function to check if mid >= Kth smallest multiple
def check(mid, arr, K):
    # Variable to store the count of multiples till K
    count = 0
    
    # Iterate through all subsets of the array elements
    for i in range(1, 1 << len(arr)):
        product = 1
        sign = True
        # Calculate the product of elements in the subset
        for j in range(len(arr)):
            if i & (1 << j):
                product *= arr[j]
                sign = not sign
        # Update count based on the product and sign
        if sign:
            count -= mid // product
        else:
            count += mid // product
    
    return count >= K

# Function to find the Kth smallest multiple
def solve(arr, K):
    low, hi = 0, 10**18
    N = len(arr)
    res = 0
    
    while low <= hi:
        mid = low + (hi - low) // 2
        if check(mid, arr, K):
            res = mid
            hi = mid - 1
        else:
            low = mid + 1
    
    return res

# Main function
if __name__ == "__main__":
    k = 5
    arr = [3, 5, 7]
    print("The 5th number to be selected on the number line is:", solve(arr, k))
JavaScript
// Function to check if mid >= Kth smallest multiple
function check(mid, arr, N, K) {
    // Variable to store the count of multiples till K
    let count = 0;

    for (let i = 1; i < (1 << N); i++) {
        let product = 1;
        let sign = true;
        for (let j = 0; j < N; j++) {
            if (i & (1 << j)) {
                product *= arr[j];
                sign = !sign;
            }
        }
        if (sign) {
            count -= Math.floor(mid / product);
        } else {
            count += Math.floor(mid / product);
        }
    }
    return count >= K;
}

// Function to find the Kth smallest multiple
function solve(arr, K) {
    let low = 0, hi = 1e18;
    let N = arr.length;
    let res = 0;

    while (low <= hi) {
        let mid = low + Math.floor((hi - low) / 2);
        if (check(mid, arr, N, K)) {
            res = mid;
            hi = mid - 1;
        } else {
            low = mid + 1;
        }
    }
    return res;
}

// Main function
function main() {
    let k = 5;
    let arr = [3, 5, 7];
    console.log("The 5th number to be selected on the number line is: " + solve(arr, k));
}

// Calling the main function
main();

Output
The 5th number to be selected on the number line is: 9

Time Complexity: O(N * (2 ^ N) * log(K))
Auxiliary Space: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads