Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Generate a sequence with product N such that for every pair of indices (i, j) and i < j, arr[j] is divisible by arr[i]
Next article icon

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

Last Updated : 04 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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. 
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
<script>  // JavaScript program for the above approach  // Function to construct longest array     // with product K such that each element     // is divisible by its previous element function findLongestArray(K) {     // Stores the prime factors of K         let primefactors = [];           let K_temp = K;           for (let i = 2; i * i <= K; i++) {               // Stores the power to which             // primefactor i is raised             let count = 0;               while (K_temp % i == 0) {                 K_temp = Math.floor(K_temp/i);                 count++;             }               if (count > 0)                 primefactors.push([ count, i ]);         }           if (K_temp != 1)             primefactors.push([ 1, K_temp ]);           // Sort prime factors in descending order         primefactors.sort(function(x, y) {             if (x[0] != y[0])                 return y[0] - x[0];             return y[1] - x[1];         });           // Stores the final array         let n = primefactors[0][0];         let val = primefactors[0][1];         let answer = new Array(n);         for(let i=0;i<n;i++)         {             answer[i]=val;         }           // Multiply the last element by K         answer[n - 1] *= K;           for (let i = 0; i < n; i++) {             answer[n - 1] = Math.floor(answer[n - 1]/val);         }           // Print the constructed array         document.write("{");         for (let i = 0; i < answer.length; i++) {             if (i == answer.length - 1)                 document.write(answer[i] + "}");             else                 document.write(answer[i] + ", ");         } }  // Driver Code let K = 4; findLongestArray(K);  // This code is contributed by avanitrachhadiya2155  </script> 

 
 


Output: 
{2, 2}

 

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


Next Article
Generate a sequence with product N such that for every pair of indices (i, j) and i < j, arr[j] is divisible by arr[i]

P

pkjrockzz
Improve
Article Tags :
  • Greedy
  • Mathematical
  • DSA
  • Arrays
  • prime-factor
Practice Tags :
  • Arrays
  • Greedy
  • Mathematical

Similar Reads

  • Generate a sequence with product N such that for every pair of indices (i, j) and i < j, arr[j] is divisible by arr[i]
    Given a positive integer N, the task is to generate a sequence say arr[] of maximum length having all elements at least 2 such that the product of all the numbers in the sequence is N and for any pair of indices (i, j) and i < j, arr[j] is divisible by arr[i]. Examples: Input: N = 360Output: Maxi
    11 min read
  • Generate an N-length array having maximum element minimized and sum of array elements divisible by K
    Given two positive integers N and K, the task is to minimize the maximum element of the array formed such that the sum of array elements is positive and divisible by K. Examples: Input: N = 4, K = 50Output: 13Explanation The generated array is {12, 13, 12, 13}. Sum of the array is 50, which is divis
    3 min read
  • Generate an array with product of all subarrays of length exceeding one divisible by K
    Given two positive integers N and K, the task is to generate an array of length N such that the product of every subarray of length greater than 1 must be divisible by K and the maximum element of the array must be less than K. If no such array is possible, then print -1. Examples: Input: N = 3, K =
    6 min read
  • Sum of array elements possible by appending arr[i] / K to the end of the array K times for array elements divisible by K
    Given an array arr[] consisting of N integers and an integer K, the task is to find the sum of the array elements possible by traversing the array and adding arr[i] / K, K number of times at the end of the array, if arr[i] is divisible by K. Otherwise, stop the traversal. Examples: Input: arr[] = {4
    14 min read
  • Generate an Array such that the sum of any Subarray is not divisible by its Length
    Given an integer N. Then the task is to output an array let's say A[] of length N such that: The sum S, of any subarray, let's say A[L, R] where (L != R) must not leave the remainder as 0 when dividing by the length of A[L, R]. Formally, Sum(A[L, R])%(length of A[L, R]) != 0. A[] must contain all un
    5 min read
  • Construct Array of given size with elements at even positions divisible by their adjacent left
    Given an integer N, the task is to construct and print an Array, such that: The size of array is NThe elements in array are in range [1, 2*N]Each element in the array are distinctThe elements at even positions are divisible by their adjacent left, but this must not be true for odd position elements,
    11 min read
  • Count ways to generate N-length array with 0s, 1s, and 2s such that sum of all adjacent pairwise products is K
    Given two integers N and K, the task is to find the number of N-length arrays that can be generated by using the values 0, 1, and 2 any number of times, such that the sum of all adjacent pairwise products of the array is K. Examples: Input: N = 4, K = 3Output: 5Explanation: All possible arrangements
    15+ min read
  • Generate an array of K elements such that sum of elements is N and the condition a[i] < a[i+1] <= 2*a[i] is met | Set 2
    Given two integers N and K, the task is to generate an array arr[] of length K such that: arr[0] + arr[1] + ... + arr[K - 1] = N.arr[i] > 0 for 0 ? i < K.arr[i] < arr[i + 1] ? 2 * arr[i] for 0 ? i < K - 1. If there are multiple answers find any one of them, otherwise, print -1. Examples:
    12 min read
  • Count arrays of length K whose product of elements is same as that of given array
    Given an integer array arr[] of length N and an integer K, the task is to count the number of possible arrays of length K such that the product of all elements of that array is equal to the product of all elements of the given array arr[]. Since the answer can be very large, return the answer modulo
    15+ min read
  • Check if all array elements can be made divisible by K by replacing array elements with sum of pairs
    Given an array arr[] of size N and a positive integer K, the task is to make every element of the array divisible by K by repeatedly selecting a pair of indices (i, j) and perform arr[i] = arr[i] + arr[j]. Examples: Input: arr[] = {3, 6, 3}, K = 6Output: TrueExplanation: Update arr[0] = arr[0] + arr
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences