# Generate longest possible array with product K such that each array element is divisible by its previous adjacent element

Last Updated : 04 Jan, 2023

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 ` `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 > 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.`

## C#

 `using` `System;` `using` `System.Collections.Generic;` `using` `System.Linq;`   `namespace` `ConsoleApp` `{` `  ``class` `Program` `  ``{` `    ``// 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` `      ``List<``int``[]> primefactors = ``new` `List<``int``[]>();`   `      ``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` `      ``primefactors = primefactors.OrderByDescending(x => x[0]).ThenByDescending(y => y[1]).ToList();`   `      ``// Stores the final array` `      ``int` `n = primefactors[0][0];` `      ``int` `val = primefactors[0][1];` `      ``int``[] answer = ``new` `int``[n];` `      ``for` `(``int` `i = 0; i < answer.Length; i++)` `      ``{` `        ``answer[i] = 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` `      ``Console.Write(``"{"``);` `      ``for` `(``int` `i = 0; i < answer.Length; i++)` `      ``{` `        ``if` `(i == answer.Length - 1)` `          ``Console.Write(answer[i] + ``"}"``);` `        ``else` `          ``Console.Write(answer[i] + ``", "``);` `      ``}` `    ``}`   `    ``// Driver Code` `    ``static` `void` `Main(``string``[] args)` `    ``{` `      ``int` `K = 4;` `      ``FindLongestArray(K);` `    ``}` `  ``}` `}`   `// This code is contributed by phasing17.`

## Javascript

 ``

Output:

`{2, 2}`

Time Complexity: O(âˆš(K) * log(âˆš(K)))
Auxiliary Space: O(âˆš(K))