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 <bits/stdc++.h>using namespace std;Â
// Function to find the sum of the matrixint 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 Codeint main(){Â Â Â Â int M = 3, N = 4;Â
    // Function Call    cout << summation(M, N);    return 0;} |
Java
// Java Code to Implement the approachimport 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 matrixdef 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 = 3N = 4# Function callprint(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
<script>// Javascript Code to Implement the approachÂ
// Function to find the sum of the matrixfunction summation(M, N){Â Â Â Â let matrix = [];Â Â Â Â let sum =0;Â Â Â Â Â Â Â Â Â for(let i=0;i<M;i++)Â Â Â Â {matrix[i] = [];Â Â Â Â Â Â Â Â for(let j=0;j<N;j++){Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â matrix[i][j] = 0 Â Â Â Â Â Â Â Â }Â Â Â Â }Â
    // Loop to form the matrix and find its sum    for (let i = 0; i < M; i++) {        for (let 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    let M = 3;    let N = 4;Â
    // Function Call    console.log(summation(M, N));         // This code is contributed by akashish__Â
</script> |
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 timeTotal 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 <bits/stdc++.h>using namespace std;Â
// Function to find the sum of the matrixint 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 Codeint main(){Â Â Â Â int M = 3, N = 4;Â
    // Function Call    cout << summation(M, N);    return 0;} |
Java
// Java Code to Implement the Ideaimport 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 codeif __name__ == "__main__" :         M , N = 3, 4;Â
    # Function Call    print(summation(M, N))Â
# this code is contributed by aditya942003patil |
C#
// C# code to implement the approachusing 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 Codepublic static void Main(){    int M = 3, N = 4;Â
    // Function Call    Console.WriteLine(summation(M, N));Â
}}Â Â // This code is contributed by aditya942003patil |
Javascript
<script>// Javascript code to implement the approach.Â
// Function to find the sum of the matrixfunction summation(M, N){Â Â Â Â let sum = 0, start = M + N, i;Â
    for (i = 1; i <= M; i++) {        if (i >= N) {            sum += start * N;        }        else {            sum += start * i;        }        start--;    }    for (i = N - 1; i >= 1; i--) {        if (i >= M) {            sum += start * M;        }        else {            sum += start * i;        }        start--;    }Â
    // Return the sum    return sum;     }      let M = 3, N = 4;Â
    // Function Call    document.write(summation(M, N));Â
          // This code is contributed by aditya942003patil.   </script> |
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.
- Finally return total sum .
Below is the implementation of the above approach:Â Â
C++
// C++ Code to Implement the IdeaÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to find the total sum of the elements in the matrixint 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 Codeint 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 matrixdef 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 Codeif __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 matrixfunction 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 Codelet M = 3,N = 4;Â
// Function Callconsole.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));    }} |
54
Time Complexity: O(1)
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



