Skip to content
Related Articles

Related Articles

Generate longest possible array with product K such that each array element is divisible by its previous adjacent element
  • Last Updated : 23 Mar, 2021

Given an integer K, the task is to construct an array of maximum length with product of all array elements equal to K, such that each array element except the first one is divisible by its previous adjacent element.
Note: Every array element in the generated array must be greater than 1.

Examples: 

Input: K = 4
Output: {2, 2}
Explanation:
The second element, i.e. arr[1] (= 2) is divisible by the first element, i.e. arr[0] (= 2).
Product of the array elements = 2 * 2 = 4(= K). 
Therefore, the array satisfies the required condition.

Input: K = 23
Output: {23}

 

Approach: The idea to solve this problem is to find all the prime factors of K with their respective powers such that:

prime_factor[1]x * prime_factor[2]y … * primefactor[i]z = K



Follow the steps below to solve this problem:

  • Find the prime factor, say X, with the greatest power, say Y.
  • Then, Y will be the length of the required array.
  • Therefore, construct an array of length Y with all elements in it equal to X.
  • To make the product of array equal to K, multiply the last element by K / X y.

Below is the implementation of the above approach: 

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to construct longest array
// with product K such that each element
// is divisible by its previous element
void findLongestArray(int K)
{
    // Stores the prime factors of K
    vector<pair<int, int> > primefactors;
 
    int K_temp = K;
 
    for (int i = 2; i * i <= K; i++) {
 
        // Stores the power to which
        // primefactor i is raised
        int count = 0;
 
        while (K_temp % i == 0) {
            K_temp /= i;
            count++;
        }
 
        if (count > 0)
            primefactors.push_back({ count, i });
    }
 
    if (K_temp != 1)
        primefactors.push_back(
            { 1, K_temp });
 
    // Sort prime factors in descending order
    sort(primefactors.rbegin(),
         primefactors.rend());
 
    // Stores the final array
    vector<int> answer(
        primefactors[0].first,
        primefactors[0].second);
 
    // Multiply the last element by K
    answer.back() *= K;
 
    for (int i = 0;
         i < primefactors[0].first; i++) {
        answer.back() /= primefactors[0].second;
    }
 
    // Print the constructed array
    cout << "{";
    for (int i = 0; i < (int)answer.size(); i++) {
        if (i == answer.size() - 1)
            cout << answer[i] << "}";
        else
            cout << answer[i] << ", ";
    }
}
 
// Driver Code
int main()
{
    int K = 4;
    findLongestArray(K);
}

Java




// java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG {
 
    // Function to construct longest array
    // with product K such that each element
    // is divisible by its previous element
    static void findLongestArray(int K)
    {
        // Stores the prime factors of K
        ArrayList<int[]> primefactors = new ArrayList<>();
 
        int K_temp = K;
 
        for (int i = 2; i * i <= K; i++) {
 
            // Stores the power to which
            // primefactor i is raised
            int count = 0;
 
            while (K_temp % i == 0) {
                K_temp /= i;
                count++;
            }
 
            if (count > 0)
                primefactors.add(new int[] { count, i });
        }
 
        if (K_temp != 1)
            primefactors.add(new int[] { 1, K_temp });
 
        // Sort prime factors in descending order
        Collections.sort(primefactors, (x, y) -> {
            if (x[0] != y[0])
                return y[0] - x[0];
            return y[1] - x[1];
        });
 
        // Stores the final array
        int n = primefactors.get(0)[0];
        int val = primefactors.get(0)[1];
        int answer[] = new int[n];
        Arrays.fill(answer, val);
 
        // Multiply the last element by K
        answer[n - 1] *= K;
 
        for (int i = 0; i < n; i++) {
            answer[n - 1] /= val;
        }
 
        // Print the constructed array
        System.out.print("{");
        for (int i = 0; i < answer.length; i++) {
            if (i == answer.length - 1)
                System.out.print(answer[i] + "}");
            else
                System.out.print(answer[i] + ", ");
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        int K = 4;
        findLongestArray(K);
    }
}
 
// This code is contributed by Kingash.

Python3




# Python 3 program for the above approach
 
# Function to construct longest array
# with product K such that each element
# is divisible by its previous element
def findLongestArray(K):
 
    # Stores the prime factors of K
    primefactors = []
 
    K_temp = K
 
    i = 2
    while i * i <= K:
 
        # Stores the power to which
        # primefactor i is raised
        count = 0
 
        while (K_temp % i == 0):
            K_temp //= i
            count += 1
 
        if (count > 0):
            primefactors.append([count, i])
 
        i += 1
 
    if (K_temp != 1):
        primefactors.append(
            [1, K_temp])
 
    # Sort prime factors in descending order
    primefactors.sort()
 
    # Stores the final array
    answer = [primefactors[0][0],
              primefactors[0][1]]
 
    # Multiply the last element by K
    answer[-1] *= K
 
    for i in range(primefactors[0][0]):
        answer[-1] //= primefactors[0][1]
 
    # Print the constructed array
    print("{", end = "")
    for i in range(len(answer)):
        if (i == len(answer) - 1):
            print(answer[i], end = "}")
        else:
            print(answer[i], end = ", ")
 
# Driver Code
if __name__ == "__main__":
    K = 4
    findLongestArray(K)
 
    # This code is contributed by ukasp.

 
 

Output: 
{2, 2}

 

Time Complexity: O(√(K) * log(√(K)))
Auxiliary Space: O(√(K)) 

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :