由无限连接给定数组形成的 Array 的前 M 个元素的总和
给定一个由N个整数和一个正整数M组成的数组arr[] ,任务是找到由给定数组arr[]的无限级联形成的数组的前M个元素的总和。
例子:
Input: arr[] = {1, 2, 3}, M = 5
Output: 9
Explanation:
The array formed by the infinite concatenation of the given array arr[] is of the form {1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, … }.
The sum of the first M(= 5) elements of the array is 1 + 2 + 3 + 1 + 2 = 9.
Input: arr[] = {1}, M = 7
Output: 7
方法:给定的问题可以通过使用模运算符 (%)来解决 并将给定的数组视为循环数组,并相应地找到前M个元素的总和。请按照以下步骤解决此问题:
- 初始化一个变量,比如sum为0以存储新数组的前M个元素的总和。
- 使用变量i在[0, M – 1]范围内迭代,并将sum的值增加arr[i%N] 。
- 完成上述步骤后,打印sum的值作为结果。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to find the sum of first
// M numbers formed by the infinite
// concatenation of the array A[]
int sumOfFirstM(int A[], int N, int M)
{
// Stores the resultant sum
int sum = 0;
// Iterate over the range [0, M - 1]
for (int i = 0; i < M; i++) {
// Add the value A[i%N] to sum
sum = sum + A[i % N];
}
// Return the resultant sum
return sum;
}
// Driver Code
int main()
{
int arr[] = { 1, 2, 3 };
int M = 5;
int N = sizeof(arr) / sizeof(arr[0]);
cout << sumOfFirstM(arr, N, M);
return 0;
}
Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
class GFG {
// Function to find the sum of first
// M numbers formed by the infinite
// concatenation of the array A[]
public static int sumOfFirstM(int A[], int N, int M)
{
// Stores the resultant sum
int sum = 0;
// Iterate over the range [0, M - 1]
for (int i = 0; i < M; i++) {
// Add the value A[i%N] to sum
sum = sum + A[i % N];
}
// Return the resultant sum
return sum;
}
// Driver Code
public static void main(String[] args) {
int arr[] = { 1, 2, 3 };
int M = 5;
int N = arr.length;
System.out.println(sumOfFirstM(arr, N, M));
}
}
// This code is contributed by gfgking.
Python3
# Python3 program for the above approach
# Function to find the sum of first
# M numbers formed by the infinite
# concatenation of the array A[]
def sumOfFirstM(A, N, M):
# Stores the resultant sum
sum = 0
# Iterate over the range [0, M - 1]
for i in range(M):
# Add the value A[i%N] to sum
sum = sum + A[i % N]
# Return the resultant sum
return sum
# Driver Code
if __name__ == '__main__':
arr = [ 1, 2, 3 ]
M = 5
N = len(arr)
print(sumOfFirstM(arr, N, M))
# This code is contributed by ipg2016107
C#
// C# program for the above approach
using System;
class GFG {
// Function to find the sum of first
// M numbers formed by the infinite
// concatenation of the array A[]
static int sumOfFirstM(int[] A, int N, int M)
{
// Stores the resultant sum
int sum = 0;
// Iterate over the range [0, M - 1]
for (int i = 0; i < M; i++) {
// Add the value A[i%N] to sum
sum = sum + A[i % N];
}
// Return the resultant sum
return sum;
}
// Driver Code
public static void Main()
{
int[] arr = { 1, 2, 3 };
int M = 5;
int N = arr.Length;
Console.WriteLine(sumOfFirstM(arr, N, M));
}
}
// This code is contributed by subhammahato348.
Javascript
输出:
9
时间复杂度: O(M)
辅助空间: O(1)