给定一个整数N ,任务是制作一个长度为N的唯一元素数组,以使所有子数组的模N的总和等于零。
例子:
Input: N = 6
Output: 6 12 18 24 30 36
Explanation:
Since all elements are a muliple of 6. Hence all subarrays add up to a sum divisible by 6.
Input: N = 4
Output: 4 8 12 16
方法:
我们可以观察到,要使所有子数组都能被N整除,则数组的元素必须是N的倍数。
插图:
For N = 4, if we consider the array elements to {4, 8, 12, 16}, All possible subarrays are:
{4}, {8}, {12}, {16}, {4, 8}, {8, 12}, {12, 16}, {4, 8, 12}, {8, 12, 16}, {4, 8, 12, 16}
Hence, all subarrays have a sum divisible by N.
因此,要解决该问题,我们只需要打印{N,2 * N,3 * N,…..,N * N}即可获得所需的数组。
下面是上述方法的实现:
C++
// C++ implementation of the
// above approach
#include
using namespace std;
// Function to print the required
// array
void makeArray(int a[], int n)
{
// Print the array
for (int i = 1; i <= n; i++)
cout << i * n << " ";
}
// Driver Program
int main()
{
int N = 6;
int arr[N];
makeArray(arr, N);
}
Java
// Java program for the above approach
class GFG{
// Function to print the required
// array
static void makeArray(int a[], int n)
{
// Print the array
for(int i = 1; i <= n; i++)
System.out.print(i * n + " ");
}
// Driver code
public static void main(String[] args)
{
int N = 6;
int arr[] = new int[N];
makeArray(arr, N);
}
}
// This code is contributed by Pratima Pandey
Python3
# Python3 implementation of the
# above approach
# Function to print the
# required array
def makeArray(n):
# Print Array
for i in range(n):
print((i + 1) * n, end =" ")
# Driver code
n = 6;
makeArray(n);
C#
// C# program for the above approach
using System;
class GFG{
// Function to print the required
// array
static void makeArray(int []a, int n)
{
// Print the array
for(int i = 1; i <= n; i++)
Console.Write(i * n + " ");
}
// Driver code
public static void Main()
{
int N = 6;
int []arr = new int[N];
makeArray(arr, N);
}
}
// This code is contributed by Code_Mech
输出:
6 12 18 24 30 36
时间复杂度: O(N)
辅助空间: O(1)