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

📅  最后修改于: 2021-09-06 05:41:59             🧑  作者: Mango

给定三个整数NKX ,任务是创建一个长度为N的数组,其所有 K 长度子数组的模N 之和X
例子:

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

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

  • 0N – 1迭代i ,以打印所需子数组的第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


Javascript


输出:
9 6 6 9 6 6

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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live