Given a positive integer N, the task is to generate an array such that the sum of the Euler Totient Function of each element is equal to N.
Examples:
Input: N = 6
Output: 1 6 2 3
Input: N = 12
Output: 1 12 2 6 3 4
Approach: The given problem can be solved based on the divisor sum property of the Euler Totient Function, i.e.,
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void constructArray( int N)
{
vector< int > ans;
for ( int i = 1; i * i <= N; i++) {
if (N % i == 0) {
ans.push_back(i);
if (N != (i * i)) {
ans.push_back(N / i);
}
}
}
for ( auto it : ans) {
cout << it << " " ;
}
}
int main()
{
int N = 12;
constructArray(N);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void constructArray( int N)
{
ArrayList<Integer> ans = new ArrayList<Integer>();
for ( int i = 1 ; i * i <= N; i++)
{
if (N % i == 0 )
{
ans.add(i);
if (N != (i * i))
{
ans.add(N / i);
}
}
}
for ( int it : ans)
{
System.out.print(it + " " );
}
}
public static void main(String[] args)
{
int N = 12 ;
constructArray(N);
}
}
|
Python3
from math import sqrt
def constructArray(N):
ans = []
for i in range ( 1 , int (sqrt(N)) + 1 , 1 ):
if (N % i = = 0 ):
ans.append(i)
if (N ! = (i * i)):
ans.append(N / i)
for it in ans:
print ( int (it), end = " " )
if __name__ = = '__main__' :
N = 12
constructArray(N)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void constructArray( int N)
{
List< int > ans = new List< int >();
for ( int i = 1; i * i <= N; i++)
{
if (N % i == 0)
{
ans.Add(i);
if (N != (i * i))
{
ans.Add(N / i);
}
}
}
foreach ( int it in ans)
{
Console.Write(it + " " );
}
}
public static void Main()
{
int N = 12;
constructArray(N);
}
}
|
Javascript
<script>
function constructArray(N)
{
var ans = [];
for ( var i = 1; i * i <= N; i++)
{
if (N % i == 0)
{
ans.push(i);
if (N != (i * i))
{
ans.push(N / i);
}
}
}
document.write(ans);
}
var N = 12;
constructArray(N);
</script>
|
Time Complexity: O(√N)
Auxiliary Space: O(N)