Given two positive integers N and K, the task is to generate an array consisting of N distinct integers such that the sum of elements of each subarray of the constructed array is divisible by K.
Examples:
Input: N = 3, K = 3
Output: 3 6 9
Explanation:
The subarrays of the resultant array are {3}, {6}, {3, 6}, {9}, {6, 9}, {3, 6, 9}. Sum of all these subarrays are divisible by K.
Input: N = 5, K = 1
Output: 1 2 3 4 5
Approach: Follow the steps below to solve the problem:
- Since the sum of elements of each subarray needs to be divisible by K, the most optimal approach would be to construct an array with each element being a multiple of K.
- Therefore, iterate a loop from i = 1 to i = N and for each value of i, print K * i.
Below is the implementation of the above approach:
C++14
#include <bits/stdc++.h>
using namespace std;
void construct_Array( int N, int K)
{
for ( int i = 1; i <= N; i++) {
cout << K * i << " " ;
}
}
int main()
{
int N = 3, K = 3;
construct_Array(N, K);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG
{
static void construct_Array( int N, int K)
{
for ( int i = 1 ; i <= N; i++)
{
System.out.print(K * i + " " );
}
}
public static void main(String[] args)
{
int N = 3 , K = 3 ;
construct_Array(N, K);
}
}
|
Python3
def construct_Array(N, K) :
for i in range ( 1 , N + 1 ):
print (K * i, end = " " )
N = 3
K = 3
construct_Array(N, K)
|
C#
using System;
public class GFG
{
static void construct_Array( int N, int K)
{
for ( int i = 1; i <= N; i++)
{
Console.Write(K * i + " " );
}
}
public static void Main(String[] args)
{
int N = 3, K = 3;
construct_Array(N, K);
}
}
|
Javascript
<script>
function construct_Array(N, K)
{
for (let i = 1; i <= N; i++) {
document.write( K * i + " " );
}
}
let N = 3, K = 3;
construct_Array(N, K);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)