📌  相关文章
📜  生成其所有K大小子数组的总和除以N个叶子余数X的数组

📅  最后修改于: 2021-05-17 21:08:34             🧑  作者: Mango

给出三个整N,KX,该任务是创建长度N SUACH的阵列,其所有的K-长度子阵列的总和模NX。

例子:

方法:
我们可以观察到,为了使大小为KN的子数组的总和等于X ,子数组需要具有K – 1个元素等于N和1个元素等于N +X

插图:

因此,请按照以下步骤解决问题:

  • i0迭代到N – 1 ,以打印所需子数组的第i元素。
  • 如果i%K等于0 ,则打印N +X 。否则,对于i的所有其他值打印N。
  • 这确保了每个可能的K长度子数组都有一个和K * N + X。因此,对于所有这样的子阵列,求和模NX。

下面是上述方法的实现。

C++
// C++ implementation of the
// above approach
#include 
using namespace std;
  
// Funtion prints the required array
void createArray(int n, int k, int x)
{
    for (int i = 0; i < n; i++) {
        // First element of each K
        // length subarrays
        if (i % k == 0) {
            cout << x + n << " ";
        }
        else {
            cout << n << " ";
        }
    }
}
  
// Driver Program
int main()
{
  
    int N = 6, K = 3, X = 3;
    createArray(N, K, X);
}


Java
// Java implementation of the above approach
import java.util.*;
class GFG{
  
// Function prints the required array
static void createArray(int n, int k, int x)
{
    for(int i = 0; i < n; i++)
    {
          
       // First element of each K
       // length subarrays
       if (i % k == 0) 
       {
           System.out.print((x + n) + " ");
       }
       else
       {
           System.out.print(n + " ");
       }
    }
}
  
// Driver Code
public static void main(String args[])
{
    int N = 6, K = 3, X = 3;
      
    createArray(N, K, X);
}
}
  
// This code is contributed by Code_Mech


Python3
# Python3 implementation of the 
# above approach 
  
# Funtion prints the required array 
def createArray(n, k, x):
      
    for i in range(n):
          
        # First element of each K
        # length subarrays
        if (i % k == 0):
            print(x + n, end = " ")
        else :
            print(n, end = " ")
  
# Driver code
N = 6
K = 3
X = 3
  
createArray(N, K, X)
  
# This code is contributed by Vishal Maurya.


C#
// C# implementation of the above approach
using System;
class GFG{
  
// Function prints the required array
static void createArray(int n, int k, int x)
{
    for(int i = 0; i < n; i++)
    {
         
       // First element of each K
       // length subarrays
       if (i % k == 0) 
       {
           Console.Write((x + n) + " ");
       }
       else
       {
           Console.Write(n + " ");
       }
    }
}
  
// Driver Code
public static void Main()
{
    int N = 6, K = 3, X = 3;
      
    createArray(N, K, X);
}
}
  
// This code is contributed by Code_Mech


输出:
9 6 6 9 6 6

时间复杂度: O(N)
辅助空间: O(1)