Sum of the first M elements of Array formed by infinitely concatenating given array
Last Updated :
16 Jul, 2021
Given an array arr[] consisting of N integers and a positive integer M, the task is to find the sum of the first M elements of the array formed by the infinite concatenation of the given array arr[].
Examples:
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
Approach: The given problem can be solved by using the Modulo Operator (%) and consider the given array as the circular array and find the sum of the first M elements accordingly. Follow the steps below to solve this problem:
- Initialize a variable, say sum as 0 to store the resultant sum of the first M elements of the new array.
- Iterate over the range [0, M – 1] using the variable i and increment the value of sum by arr[i%N].
- After completing the above steps, print the value of the sum as the result.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int sumOfFirstM( int A[], int N, int M)
{
int sum = 0;
for ( int i = 0; i < M; i++) {
sum = sum + A[i % N];
}
return sum;
}
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
import java.io.*;
import java.lang.*;
class GFG {
public static int sumOfFirstM( int A[], int N, int M)
{
int sum = 0 ;
for ( int i = 0 ; i < M; i++) {
sum = sum + A[i % N];
}
return sum;
}
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));
}
}
|
Python3
def sumOfFirstM(A, N, M):
sum = 0
for i in range (M):
sum = sum + A[i % N]
return sum
if __name__ = = '__main__' :
arr = [ 1 , 2 , 3 ]
M = 5
N = len (arr)
print (sumOfFirstM(arr, N, M))
|
C#
using System;
class GFG {
static int sumOfFirstM( int [] A, int N, int M)
{
int sum = 0;
for ( int i = 0; i < M; i++) {
sum = sum + A[i % N];
}
return sum;
}
public static void Main()
{
int [] arr = { 1, 2, 3 };
int M = 5;
int N = arr.Length;
Console.WriteLine(sumOfFirstM(arr, N, M));
}
}
|
Javascript
<script>
function sumOfFirstM(A, N, M) {
let sum = 0;
for (let i = 0; i < M; i++) {
sum = sum + A[i % N];
}
return sum;
}
let arr = [1, 2, 3];
let M = 5;
let N = arr.length;
document.write(sumOfFirstM(arr, N, M));
</script>
|
Time Complexity: O(M)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...