GFG App
Open App
Browser
Continue

# Sum of Matrix where each element is sum of row and column number

Given two numbers M and N denoting the number of rows and columns of a matrix A[] where A[i][j] is the sum of i and j (indices follow 1 based indexing), the task is to find the sum of elements of the matrix.

Examples:

Input: M = 3, N = 3
Output: 36
Explanation: A[]: {{2, 3, 4}, {3, 4, 5}, {4, 5, 6}}. Sum of matrix: 36.

Input: M = 3, N = 4
Output: 54
Explanation: A[]: {{2, 3, 4, 5}, {3, 4, 5, 6}, {4, 5, 6, 7}}, Sum of matrix: 54

Naive Approach: To solve the problem follow the below idea:

Create a matrix of size M x N. While creating matrix make element at position (i, j) equal to i + j, where i and j are indices
(1 based indexing) of row and column of matrix. At last traverse on the matrix and return the sum.

Below is the implementation of the above approach:

## C++

 `// C++ Code to Implement the approach`   `#include ` `using` `namespace` `std;`   `// Function to find the sum of the matrix` `int` `summation(``int` `M, ``int` `N)` `{` `    ``int` `matrix[M][N], sum = 0;`   `    ``// Loop to form the matrix and find its sum` `    ``for` `(``int` `i = 0; i < M; i++) {` `        ``for` `(``int` `j = 0; j < N; j++) {` `            ``matrix[i][j] = (i + 1) + (j + 1);` `            ``sum += matrix[i][j];` `        ``}` `    ``}`   `    ``// Return the sum of the matrix` `    ``return` `sum;` `}`   `// Driver Code` `int` `main()` `{` `    ``int` `M = 3, N = 4;`   `    ``// Function Call` `    ``cout << summation(M, N);` `    ``return` `0;` `}`

## Java

 `// Java Code to Implement the approach` `import` `java.io.*;`   `class` `GFG {` `    ``// Function to find the sum of the matrix` `    ``public` `static` `int` `summation(``int` `M, ``int` `N)` `    ``{` `        ``int` `matrix[][] = ``new` `int``[M][N];` `        ``int` `sum = ``0``;`   `        ``// Loop to form the matrix and find its sum` `        ``for` `(``int` `i = ``0``; i < M; i++) {` `            ``for` `(``int` `j = ``0``; j < N; j++) {` `                ``matrix[i][j] = (i + ``1``) + (j + ``1``);` `                ``sum += matrix[i][j];` `            ``}` `        ``}`   `        ``// Return the sum of the matrix` `        ``return` `sum;` `    ``}`   `    ``// Driver Code` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``int` `M = ``3``, N = ``4``;`   `        ``// Function Call` `        ``System.out.print(summation(M, N));` `    ``}` `}`   `// This code is contributed by Rohit Pradhan`

## Python3

 `# Python code to implement the approach`   `# Function to find the sum of the matrix` `def` `summation(M, N):` `    ``sum` `=` `0` `    ``rows, cols ``=` `(``5``, ``5``)` `    ``matrix ``=` `[[``0``]``*``cols]``*``rows`   `    ``# Loop to form the matrix and find its sum` `    ``for` `i ``in` `range``(``0``, M):` `        ``for` `j ``in` `range``(``0``, N):` `            ``matrix[i][j] ``=` `(i``+``1``) ``+` `(j``+``1``)` `            ``sum` `+``=` `matrix[i][j]`   `    ``# Return the sum of matrix` `    ``return` `sum`   `M ``=` `3` `N ``=` `4` `# Function call` `print``(summation(M, N))`   `# This code is contributed by lokeshmvs21.`

## C#

 `// C# Code to Implement the approach`   `using` `System;`   `public` `class` `GFG {` `    ``// Function to find the sum of the matrix` `    ``public` `static` `int` `summation(``int` `M, ``int` `N)` `    ``{` `        ``int` `[,]matrix = ``new` `int``[M,N];` `        ``int` `sum = 0;`   `        ``// Loop to form the matrix and find its sum` `        ``for` `(``int` `i = 0; i < M; i++) {` `            ``for` `(``int` `j = 0; j < N; j++) {` `                ``matrix[i,j] = (i + 1) + (j + 1);` `                ``sum += matrix[i,j];` `            ``}` `        ``}`   `        ``// Return the sum of the matrix` `        ``return` `sum;` `    ``}`   `    ``// Driver Code` `    ``public` `static` `void` `Main(``string``[] args)` `    ``{` `        ``int` `M = 3, N = 4;`   `        ``// Function Call` `        ``Console.WriteLine(summation(M, N));` `    ``}` `}`   `// This code is contributed by AnkThon`

## Javascript

 ``

Output

`54`

Time Complexity: O(M*N)
Auxiliary Space: O(M*N)

Efficient Approach: The approach to this problem is based on the following observation.

The elements of the matrix are repeating certain number of times.
If observed carefully, you can see an element with value (i + j) repeats min(i+j-1, N+M – (i+j-1)) times. and the sum of elements lies in the range [2, N+M]. So traverse in the range and find the repetition and find the sum of the matrix.

Illustration:

let M = 3 and N = 4 then matrix will be: {{2, 3, 4, 5}, {3, 4, 5, 6}, {4, 5, 6, 7}}

Occurrence of elements in matrix:

2  -> 1 time
3  -> 2 times
4  -> 3 times
5 -> 3 times
6 -> 2 times
7 -> 1 time

Total Summation = 2*1 + 3*2 + 4*3 + 5*3 + 6*2 + 7*1 = 54

Follow the steps mentioned below to implement the idea:

• Create a variable sum = 0 and start = M+N.
• Traverse in a loop from i = 1 to M.
• If the current index is greater than or equal to N, increment the sum by (start * N). Otherwise, increment the sum by (start * i).
• For each iteration decrement start.
• Traverse in a loop from i = N – 1 to 0
• If the current index is greater than or equal to M, increment the sum by (start * M). Otherwise, increment the sum by (start * i).
• For each iteration decrement start
• Return the sum as the required answer.

Below is the implementation of the above approach.

## C++

 `// C++ Code to Implement the Idea`   `#include ` `using` `namespace` `std;`   `// Function to find the sum of the matrix` `int` `summation(``int` `M, ``int` `N)` `{` `    ``int` `sum = 0, start = M + N;`   `    ``for` `(``int` `i = 1; i <= M; i++) {` `        ``if` `(i >= N) {` `            ``sum += start * N;` `        ``}` `        ``else` `{` `            ``sum += start * i;` `        ``}` `        ``start--;` `    ``}` `    ``for` `(``int` `i = N - 1; i >= 1; i--) {` `        ``if` `(i >= M) {` `            ``sum += start * M;` `        ``}` `        ``else` `{` `            ``sum += start * i;` `        ``}` `        ``start--;` `    ``}`   `    ``// Return the sum` `    ``return` `sum;` `}`   `// Driver Code` `int` `main()` `{` `    ``int` `M = 3, N = 4;`   `    ``// Function Call` `    ``cout << summation(M, N);` `    ``return` `0;` `}`

## Java

 `// Java Code to Implement the Idea` `import` `java.io.*;` `import` `java.util.*; ` ` `  `class` `GFG` `{` `  ``// Function to find the sum of the matrix   ` `  ``public` `static` `int` `summation(``int` `M, ``int` `N)` `  ``{` `    ``int` `sum = ``0``, start = M + N;`   `    ``for` `(``int` `i = ``1``; i <= M; i++) {` `        ``if` `(i >= N) {` `            ``sum += start * N;` `        ``}` `        ``else` `{` `            ``sum += start * i;` `        ``}` `        ``start--;` `    ``}` `    ``for` `(``int` `i = N - ``1``; i >= ``1``; i--) {` `        ``if` `(i >= M) {` `            ``sum += start * M;` `        ``}` `        ``else` `{` `            ``sum += start * i;` `        ``}` `        ``start--;` `    ``}`   `    ``// Return the sum` `    ``return` `sum;` `  ``}    ` ` `  `  ``// Driver program to test above` `  ``public` `static` `void` `main(String[] args)` `  ``{` `    ``int` `M = ``3``, N = ``4``;`   `    ``// Function Call` `    ``System.out.println(summation(M, N));` `  ``}` `}` `//this code is contributed by aditya942003patil`

## Python3

 `# python3 implementation of above approach` `  `  `# Function to find the sum of the matrix`   `def` `summation(M, N) :` `    `  `    ``sum` `=` `0``; start ``=` `M ``+` `N;`   `    ``for` `i ``in` `range``(``1``,M``+``1``) :` `        ``if` `(i >``=` `N) :` `            ``sum` `+``=` `start ``*` `N` `        ``else` `:` `            ``sum` `+``=` `start ``*` `i` `        ``start``-``=``1` `    ``for` `i ``in` `range``(N``-``1``,``0``,``-``1``) :` `        ``if` `(i >``=` `M) :` `            ``sum` `+``=` `start ``*` `M` `        ``else` `:` `            ``sum` `+``=` `start ``*` `i` `        ``start``-``=``1`   `    ``# Return the sum` `    ``return` `sum``;` `  `  `# Driver code` `if` `__name__ ``=``=` `"__main__"` `:` `    `  `    ``M , N ``=` `3``, ``4``;`   `    ``# Function Call` `    ``print``(summation(M, N))`   `# this code is contributed by aditya942003patil`

## C#

 `// C# code to implement the approach` `using` `System;` ` `  `class` `GFG` `{` `  ``// Function to find the sum of the matrix` `  ``public` `static` `int` `summation(``int` `M, ``int` `N)` `  ``{` `    ``int` `sum = 0, start = M + N;`   `    ``for` `(``int` `i = 1; i <= M; i++) {` `        ``if` `(i >= N) {` `            ``sum += start * N;` `        ``}` `        ``else` `{` `            ``sum += start * i;` `        ``}` `        ``start--;` `    ``}` `    ``for` `(``int` `i = N - 1; i >= 1; i--) {` `        ``if` `(i >= M) {` `            ``sum += start * M;` `        ``}` `        ``else` `{` `            ``sum += start * i;` `        ``}` `        ``start--;` `    ``}`   `    ``// Return the sum` `    ``return` `sum;` `  ``}` ` `  `// Driver Code` `public` `static` `void` `Main()` `{` `    ``int` `M = 3, N = 4;`   `    ``// Function Call` `    ``Console.WriteLine(summation(M, N));`   `}` `}` ` `  `// This code is contributed by aditya942003patil`

## Javascript

 ``

Output

`54`

Time Complexity: O(M+N)
Auxiliary Space: O(1)

Another Efficient Approach( Time Optimization ): we can do following observation to find sum of all matrix elements in O(1) time .

Steps were to follow this problem:

• We can see that sum of first row is sum of first (n+1) natural number -1.First row sum = (n+1)*(n+2) /2 -1 .
• We can also observe that sum of second row is equal to sum of first row + n .and sum of third row equal to sum of second row + n. and so on for all next rows.
• So , our temp_sum equal to m*sum of first row . because there is atleast ‘sum of first row’ in every row.
• And sum of A.P series we can find by formula .
• SO , our total sum will be sum of temp_sum and sum of A.P series.

Below is the implementation of the above approach:

## C++

 `// C++ Code to Implement the Idea`   `#include ` `using` `namespace` `std;`   `// Function to find the total sum of the elements in the matrix` `int` `summation(``int` `M, ``int` `N)` `{   ``int` `N1 = N+1; ``// N! = N+1 because there is a sum of first N+1 ` `    ``int` `first_row_sum = (N1*(N1+1))/2-1;      ``// natural numbers` `    `  `    ``int` `total_sum = M * first_row_sum ;` `     ``//A.P series - N + 2*N + 3*N +......` `    `  `    ``int` `a = N; ``// first term of A.P series ` `    ``int` `d = N; ``// common difference of A.P series` `    ``int` `n = M-1; ``// n equal to no. of terms in A.P series` `    `  `    ``// USing standard formula for finding sum of A.P series` `    ``// which you have already learned in 9-10th class` `    ``int` `sum_of_AP =  (n*(2*a + (n-1)*d)) /2 ;` `    `  `     ``total_sum += sum_of_AP;`   `    ``return` `total_sum; ``// Return total sum of matrix` `}`   `// Drive Code` `int` `main()` `{` `    ``int` `M = 3, N = 4;`   `    ``// Function Call` `    ``cout << summation(M, N);` `    ``return` `0;` `}`   `// This Approach is contributed by nikhilsainiofficial546`

## Python3

 `# Python Code to Implement the Idea`   `# Function to find the total sum of the elements in the matrix` `def` `summation(M, N):` `    ``N1 ``=` `N``+``1`  `# N! = N+1 because there is a sum of first N+1 natural numbers` `    ``first_row_sum ``=` `(N1``*``(N1``+``1``))``/``/``2``-``1`   `    ``total_sum ``=` `M ``*` `first_row_sum` `    ``# A.P series - N + 2*N + 3*N +......`   `    ``a ``=` `N  ``# first term of A.P series` `    ``d ``=` `N  ``# common difference of A.P series` `    ``n ``=` `M``-``1`  `# n equal to no. of terms in A.P series`   `    ``# Using standard formula for finding sum of A.P series` `    ``# which you have already learned in 9-10th class` `    ``sum_of_AP ``=` `(n``*``(``2``*``a ``+` `(n``-``1``)``*``d)) ``/``/` `2`   `    ``total_sum ``+``=` `sum_of_AP`   `    ``return` `total_sum  ``# Return total sum of matrix`     `# Drive Code` `if` `__name__ ``=``=` `'__main__'``:` `    ``M ``=` `3` `    ``N ``=` `4`   `    ``# Function Call` `    ``print``(summation(M, N))`

## Javascript

 `// JavaScript Code to Implement the Idea`   `// Function to find the total sum of the elements in the matrix` `function` `summation(M, N)` `{` `    ``let N1 = N + 1; ``// N! = N+1 because there is a sum of first N+1 natural numbers` `    ``let first_row_sum = (N1 * (N1 + 1)) / 2 - 1;` `    `  `    ``let total_sum = M * first_row_sum;` `    ``//A.P series - N + 2N + 3N +......` `    `  `    ``let a = N; ``// first term of A.P series` `    ``let d = N; ``// common difference of A.P series` `    ``let n = M - 1; ``// n equal to no. of terms in A.P series` `   `  `    ``// Using standard formula for finding sum of A.P series` `    ``// which you have already learned in 9-10th class` `    ``let sum_of_AP = (n * (2 * a + (n - 1) * d)) / 2;` `    `  `    ``total_sum += sum_of_AP;` `    `  `    ``return` `total_sum; ``// Return total sum of matrix` `}`   `// Drive Code` `let M = 3,` `N = 4;`   `// Function Call` `console.log(summation(M, N));`

## C#

 `// C# Code to Implement the Idea`   `using` `System;`   `public` `class` `GFG{` `    ``// Function to find the total sum of the elements in the matrix` `    ``public` `static` `int` `Summation(``int` `M, ``int` `N)` `    ``{` `        ``int` `N1 = N + 1; ``// N! = N+1 because there is a sum of first N+1 ` `        ``int` `first_row_sum = (N1 * (N1 + 1)) / 2 - 1; ``// sum of first N+1 natural numbers` `        `  `        ``int` `total_sum = M * first_row_sum;`   `        ``// A.P series - N + 2*N + 3*N +...` `        ``int` `a = N; ``// first term of A.P series ` `        ``int` `d = N; ``// common difference of A.P series` `        ``int` `n = M - 1; ``// n equal to no. of terms in A.P series`   `        ``// Using standard formula for finding sum of A.P series` `        ``// which you have already learned in 9-10th class` `        ``int` `sum_of_AP = (n * (2 * a + (n - 1) * d)) / 2;`   `        ``total_sum += sum_of_AP;`   `        ``return` `total_sum; ``// Return total sum of matrix` `    ``}`   `    ``// Driver Code` `    ``public` `static` `void` `Main(``string``[] args)` `    ``{` `        ``int` `M = 3, N = 4;`   `        ``// Function Call` `        ``Console.WriteLine(Summation(M, N));` `    ``}` `}`

## Java

 `// Java Code to Implement the Idea`   `public` `class` `GFG {` `    ``// Function to find the total sum of the elements in the matrix` `    ``public` `static` `int` `summation(``int` `M, ``int` `N) {` `        ``int` `N1 = N + ``1``; ``// N! = N+1 because there is a sum of first N+1 ` `        ``int` `first_row_sum = (N1 * (N1 + ``1``)) / ``2` `- ``1``; ``// sum of first N+1 natural numbers` `        `  `        ``int` `total_sum = M * first_row_sum;`   `        ``// A.P series - N + 2*N + 3*N +...` `        ``int` `a = N; ``// first term of A.P series ` `        ``int` `d = N; ``// common difference of A.P series` `        ``int` `n = M - ``1``; ``// n equal to no. of terms in A.P series`   `        ``// Using standard formula for finding sum of A.P series` `        ``// which you have already learned in 9-10th class` `        ``int` `sum_of_AP = (n * (``2` `* a + (n - ``1``) * d)) / ``2``;`   `        ``total_sum += sum_of_AP;`   `        ``return` `total_sum; ``// Return total sum of matrix` `    ``}`   `    ``// Driver Code` `    ``public` `static` `void` `main(String[] args) {` `        ``int` `M = ``3``, N = ``4``;`   `        ``// Function Call` `        ``System.out.println(summation(M, N));` `    ``}` `}`

Output

`54`

Time Complexity: O(1)
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up