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

• Difficulty Level : Medium
• Last Updated : 09 Sep, 2022

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)

My Personal Notes arrow_drop_up