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

📅  最后修改于: 2021-04-17 15:49:58             🧑  作者: Mango

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

例子:

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

  1. 由于每个子数组的元素之和需要被K整除,因此最佳方法是构造一个数组,每个元素为K的倍数。
  2. 因此,迭代从i = 1i = N的循环,并为i的每个值打印K * i

下面是上述方法的实现:

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)