📌  相关文章
📜  生成一个长度为 N 的数组,每个子数组的总和可被 K 整除

📅  最后修改于: 2021-10-26 05:58:16             🧑  作者: Mango

给定两个正整数NK ,任务是生成一个由N 个不同整数组成的数组,使得所构造数组的每个子数组的元素总和可以被K整除。

例子:

处理方法:按照以下步骤解决问题:

  1. 由于每个子数组的元素总和需要被K整除,因此最佳方法是构造一个数组,其中每个元素都是K的倍数。
  2. 因此,迭代从i循环= 1i = 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)