给定两个正整数N和K ,任务是生成一个由N 个不同整数组成的数组,使得所构造数组的每个子数组的元素总和可以被K整除。
例子:
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 subarrayx are divisible by K.
Input: N = 5, K = 1
Output: 1 2 3 4 5
处理方法:按照以下步骤解决问题:
- 由于每个子数组的元素总和需要被K整除,因此最佳方法是构造一个数组,其中每个元素都是K的倍数。
- 因此,迭代从i循环= 1到i = N和对于i的每个值,打印K *我。
下面是上述方法的实现:
C++14
// C++ program for the above approach
#include
using namespace std;
// Function to construct an array
// with sum of each subarray
// divisible by K
void construct_Array(int N, int K)
{
// Traverse a loop from 1 to N
for (int i = 1; i <= N; i++) {
// Print i-th multiple of K
cout << K * i << " ";
}
}
// Driver Code
int main()
{
int N = 3, K = 3;
construct_Array(N, K);
return 0;
}
Java
// Java program to implement
// the above approach
import java.io.*;
import java.util.*;
class GFG
{
// Function to construct an array
// with sum of each subarray
// divisible by K
static void construct_Array(int N, int K)
{
// Traverse a loop from 1 to N
for (int i = 1; i <= N; i++)
{
// Print i-th multiple of K
System.out.print(K * i + " ");
}
}
// Driver Code
public static void main(String[] args)
{
int N = 3, K = 3;
construct_Array(N, K);
}
}
// This code is contributed by code hunt.
Python3
# Python program for the above approach
# Function to construct an array
# with sum of each subarray
# divisible by K
def construct_Array(N, K) :
# Traverse a loop from 1 to N
for i in range(1, N + 1):
# Pri-th multiple of K
print(K * i, end = " ")
# Driver Code
N = 3
K = 3
construct_Array(N, K)
# This code is contributed by splevel62.
C#
// C# program to implement
// the above approach
using System;
public class GFG
{
// Function to construct an array
// with sum of each subarray
// divisible by K
static void construct_Array(int N, int K)
{
// Traverse a loop from 1 to N
for (int i = 1; i <= N; i++)
{
// Print i-th multiple of K
Console.Write(K * i + " ");
}
}
// Driver Code
public static void Main(String[] args)
{
int N = 3, K = 3;
construct_Array(N, K);
}
}
// This code is contributed by 29AjayKumar
Javascript
输出:
3 6 9
时间复杂度: O(N)
辅助空间: O(1)