Construct longest possible sequence of unique elements with given LCM
Given a positive integer N, the task is to construct the longest sorted sequence of unique elements whose LCM of the is equal to N.
Examples:
Input: N = 12
Output: 1 2 3 4 6 12
Explanation:
LCM of {1, 2, 3, 4, 6, 12 } is N( = 12).
Therefore, the longest possible sequence is {1, 2, 3, 4, 6, 12 }.
Input: N = 9
Output: 1 3 9
Explanation:
LCM of { 1, 2, 9 } is N( = 9).
Therefore, the longest possible sequence is {1, 3, 9 }.
Approach: The problem can be solved based on the following observation:
If an array element is not a factor of N then the LCM of the array elements never be N. Therefore, the array elements must be the factor of N.
Follow the below steps to solve this problem:
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void constructArrayWithGivenLCM( int N)
{
vector< int > newArr;
for ( int i = 1; i * i <= N;
i++) {
if (N % i == 0) {
newArr.push_back(i);
if (N / i != i) {
newArr.push_back(N / i);
}
}
}
sort(newArr.begin(), newArr.end());
for ( auto i : newArr) {
cout << i << " " ;
}
}
int main()
{
int N = 12;
constructArrayWithGivenLCM(N);
return 0;
}
|
Java
import java.util.Arrays;
class GFG{
static void constructArrayWithGivenLCM( int N)
{
int newArr[] = new int [N];
int j = 0 ;
for ( int i = 1 ; i * i <= N; i++)
{
if (N % i == 0 )
{
newArr[j] = i;
j++;
if (N / i != i)
{
newArr[j] = N / i;
j++;
}
}
}
Arrays.sort(newArr);
for ( int i = j; i < N; i++)
{
System.out.print(newArr[i] + " " );
}
}
public static void main (String[] args)
{
int N = 12 ;
constructArrayWithGivenLCM(N);
}
}
|
Python3
from math import sqrt,ceil,floor
def constructArrayWithGivenLCM(N):
newArr = []
for i in range ( 1 , ceil(sqrt(N + 1 ))):
if (N % i = = 0 ):
newArr.append(i)
if (N / / i ! = i):
newArr.append(N / / i)
newArr = sorted (newArr)
for i in newArr:
print (i, end = " " )
if __name__ = = '__main__' :
N = 12
constructArrayWithGivenLCM(N)
|
C#
using System;
class GFG{
static void constructArrayWithGivenLCM( int N)
{
int []newArr = new int [N];
int j = 0;
for ( int i = 1; i * i <= N; i++)
{
if (N % i == 0)
{
newArr[j] = i;
j++;
if (N / i != i)
{
newArr[j] = N / i;
j++;
}
}
}
Array.Sort(newArr);
for ( int i = j; i < N; i++)
{
Console.Write(newArr[i] + " " );
}
}
public static void Main(String[] args)
{
int N = 12;
constructArrayWithGivenLCM(N);
}
}
|
Javascript
<script>
function constructArrayWithGivenLCM(N)
{
let newArr = new Array(N);
newArr.fill(0);
let j = 0;
for (let i = 1; i * i <= N; i++)
{
if (N % i == 0)
{
newArr[j] = i;
j++;
if (parseInt(N / i, 10) != i)
{
newArr[j] = parseInt(N / i, 10);
j++;
}
}
}
newArr.sort( function (a, b){ return a - b});
for (let i = j; i < N; i++)
{
document.write(newArr[i] + " " );
}
}
let N = 12;
constructArrayWithGivenLCM(N);
</script>
|
Time Complexity: O(? N)
Auxiliary Space: O(1)
Last Updated :
11 Jun, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...