Given a positive integer n. Consider a matrix of n rows and n columns, in which each element contain absolute difference of its row number and numbers. The task is to calculate sum of each element of the matrix.
Examples :
Input : n = 2 Output : 2 Matrix formed with n = 2 with given constraint: 0 1 1 0 Sum of matrix = 2. Input : n = 3 Output : 8 Matrix formed with n = 3 with given constraint: 0 1 2 1 0 1 2 1 0 Sum of matrix = 8.
Method 1 (Brute Force): Simply construct a matrix of n rows and n columns and initialize each cell with absolute difference of its corresponding row number and column number. Now, find the sum of each cell.
Below is the implementation of above idea :
C++
| // C++ program to find sum of matrix in which each // element is absolute difference of its corresponding // row and column number row. #include<bits/stdc++.h> usingnamespacestd;  // Return the sum of matrix in which each element // is absolute difference of its corresponding row // and column number row intfindSum(intn) {     // Generate matrix     intarr[n][n];     for(inti = 0; i < n; i++)         for(intj = 0; j < n; j++)             arr[i][j] = abs(i - j);      // Compute sum     intsum = 0;     for(inti = 0; i < n; i++)         for(intj = 0; j < n; j++)             sum += arr[i][j];      returnsum; }  // Driven Program intmain() {     intn = 3;     cout << findSum(n) << endl;     return0; }  | 
Java
| // Java program to find sum of matrix // in which each element is absolute // difference of its corresponding // row and column number row. importjava.io.*;  publicclassGFG {  // Return the sum of matrix in which // each element is absolute difference // of its corresponding row and column // number row staticintfindSum(intn) {          // Generate matrix     int[][]arr = newint[n][n];     for(inti = 0; i < n; i++)         for(intj = 0; j < n; j++)             arr[i][j] = Math.abs(i - j);      // Compute sum     intsum = 0;     for(inti = 0; i < n; i++)         for(intj = 0; j < n; j++)             sum += arr[i][j];      returnsum; }      // Driver Code     staticpublicvoidmain (String[] args)     {         intn = 3;         System.out.println(findSum(n));     } }  // This code is contributed by vt_m.  | 
Python3
| # Python3 program to find sum of matrix  # in which each element is absolute  # difference of its corresponding # row and column number row.  # Return the sum of matrix in which each  # element is absolute difference of its  # corresponding row and column number row deffindSum(n):      # Generate matrix     arr =[[0forx inrange(n)]               fory inrange(n)]     fori inrange(n):         forj inrange(n):             arr[i][j] =abs(i -j)      # Compute sum     sum=0    fori inrange(n):         forj inrange(n):             sum+=arr[i][j]      returnsum # Driver Code if__name__ =="__main__":      n =3    print(findSum(n))      # This code is contributed by ita_c  | 
C#
| // C# program to find sum of matrix // in which each element is absolute // difference of its corresponding // row and column number row. usingSystem;  publicclassGFG {  // Return the sum of matrix in which // each element is absolute difference // of its corresponding row and column // number row staticintfindSum(intn) {      // Generate matrix     int[,]arr = newint[n, n];     for(inti = 0; i < n; i++)         for(intj = 0; j < n; j++)             arr[i,j ] = Math.Abs(i - j);       // Compute sum     intsum = 0;     for(inti = 0; i < n; i++)         for(intj = 0; j < n; j++)             sum += arr[i, j];       returnsum; }      // Driver Code     staticpublicvoidMain(String[] args)     {         intn = 3;         Console.WriteLine(findSum(n));     } }  // This code is contributed by vt_m.  | 
PHP
| <?php // PHP program to find sum of  // matrix in which each element // is absolute difference of  // its corresponding row and  // column number row.  // Return the sum of matrix  // in which each element // is absolute difference  // of its corresponding row // and column number row functionfindSum( $n) {          // Generate matrix     $arr=array(array());     for($i= 0; $i< $n; $i++)         for($j= 0; $j< $n; $j++)             $arr[$i][$j] = abs($i- $j);      // Compute sum     $sum= 0;     for($i= 0; $i< $n; $i++)         for($j= 0; $j< $n; $j++)             $sum+= $arr[$i][$j];      return$sum; }      // Driver Code     $n= 3;     echofindSum($n);  // This code is contributed by anuj_67. ?>  | 
Javascript
| <script> // Javascript program to find sum of matrix // in which each element is absolute // difference of its corresponding // row and column number row.          // Return the sum of matrix in which     // each element is absolute difference     // of its corresponding row and column     // number row     functionfindSum(n)     {              // Generate matrix         let arr=newArray(n);         for(let i = 0; i < n; i++)         {             arr[i] = newArray(n);             for(let j = 0; j < n; j++)             {                 arr[i][j] = 0;             }         }                  for(let i = 0; i < n; i++)             for(let j = 0; j < n; j++)                 arr[i][j] = Math.abs(i - j);                // Compute sum         let sum = 0;         for(let i = 0; i < n; i++)             for(let j = 0; j < n; j++)                 sum += arr[i][j];                returnsum;     }          // Driver Code     let n = 3;     document.write(findSum(n));          // This code is contributed by avanitrachhadiya2155      </script> | 
8
Time Complexity: O(N2), as we are traversing the matrix using nested loops.
Auxiliary Space: O(N2), as we are using extra space for generating and storing the Matrix.
Method 2 (O(n)):
Consider n = 3, matrix formed will be: 
0 1 2 
1 0 1 
2 1 0
Observe, the main diagonal is always 0 since all i are equal to j. The diagonal just above and just below will always be 1 because at each cell either i is 1 greater than j or j is 1 greater than i and so on. 
Following the pattern we can see that the total sum of all the elements in the matrix will be, for each i from 0 to n, add i*(n-i)*2. 
Below is the implementation of above idea :
C++
| // C++ program to find sum of matrix in which // each element is absolute difference of its // corresponding row and column number row. #include<bits/stdc++.h> usingnamespacestd;  // Return the sum of matrix in which each // element is absolute difference of its // corresponding row and column number row intfindSum(intn) {     intsum = 0;     for(inti = 0; i < n; i++)         sum += i*(n-i);     return2*sum; }  // Driven Program intmain() {     intn = 3;     cout << findSum(n) << endl;     return0; }  | 
Java
| // Java program to find sum of matrix in which // each element is absolute difference of its // corresponding row and column number row. importjava.io.*;  classGFG {  // Return the sum of matrix in which each // element is absolute difference of its // corresponding row and column number row staticintfindSum(intn) {     intsum = 0;     for(inti = 0; i < n; i++)         sum += i * (n - i);     return2* sum; }      // Driver Code     staticpublicvoidmain(String[] args)     {         intn = 3;         System.out.println(findSum(n));     } }  // This code is contributed by vt_m.  | 
C#
| // C# program to find sum of matrix in which // each element is absolute difference of its // corresponding row and column number row. usingSystem;  classGFG {  // Return the sum of matrix in which each // element is absolute difference of its // corresponding row and column number row staticintfindSum(intn) {     intsum = 0;     for(inti = 0; i < n; i++)         sum += i * (n - i);     return2 * sum; }      // Driver Code     staticpublicvoidMain(String[] args)     {         intn = 3;         Console.WriteLine(findSum(n));     } }  // This code is contributed by vt_m.  | 
Python3
| # Python 3 program to find sum  # of matrix in which each element  # is absolute difference of its  # corresponding row and column  # number row.   # Return the sum of matrix in  # which each element is absolute  # difference of its corresponding # row and column number row  deffindSum(n):     sum=0    fori inrange(n):         sum+=i *(n -i)     return2*sum # Driver code n =3print(findSum(n))  # This code is contributed by Shrikant13  | 
PHP
| <?php // PHP program to find sum of matrix in which // each element is absolute difference of its // corresponding row and column number row.  // Return the sum of matrix in which each // element is absolute difference of its // corresponding row and column number row functionfindSum($n) {     $sum= 0;     for( $i= 0; $i< $n; $i++)         $sum+= $i* ($n- $i);     return2 * $sum; }      // Driver Code     $n= 3;     echofindSum($n);  // This code is contributed by anuj_67. ?>  | 
Javascript
| <script> // Java  script program to find sum of matrix in which // each element is absolute difference of its // corresponding row and column number row. // Return the sum of matrix in which each // element is absolute difference of its // corresponding row and column number row functionfindSum( n) {     let sum = 0;     for(let i = 0; i < n; i++)         sum += i * (n - i);     return2 * sum; }      // Driver Code             let n = 3;         document.write(findSum(n));  // This code is contributed by mohan pavan  </script> | 
8
Time Complexity: O(N), as we are only using single loop to traverse.
Auxiliary Space: O(1), as we are not using any extra space.
Method 3 (Trick): 
Consider n = 3, matrix formed will be: 
0 1 2 
1 0 1 
2 1 0
So, sum = 1 + 1 + 1 + 1 + 2 + 2. 
On Rearranging, 1 + 2 + 1 + 2 + 2 = 1 + 2 + 1 + 22. 
So, in every case we can rearrange the sum of matrix so that the answer always will be sum of first n – 1 natural number and sum of square of first n – 1 natural number. 
Sum of first n natural number = ((n)*(n + 1))/2. Sum of first n natural number = ((n)*(n + 1)*(2*n + 1)/6.
Below is the implementation of above idea :
C++
| // C++ program to find sum of matrix in which // each element is absolute difference of its // corresponding row and column number row. #include<bits/stdc++.h> usingnamespacestd;  // Return the sum of matrix in which each element // is absolute difference of its corresponding // row and column number row intfindSum(intn) {     n--;     intsum = 0;     sum += (n*(n+1))/2;     sum += (n*(n+1)*(2*n + 1))/6;     returnsum; }  // Driven Program intmain() {     intn = 3;     cout << findSum(n) << endl;     return0; }  | 
Java
| // Java program to find sum of matrix in which // each element is absolute difference of its // corresponding row and column number row. importjava.io.*;  publicclassGFG {      // Return the sum of matrix in which each element // is absolute difference of its corresponding // row and column number row staticintfindSum(intn) {     n--;     intsum = 0;     sum += (n * (n + 1)) / 2;     sum += (n * (n + 1) * (2* n + 1)) / 6;     returnsum; }      // Driver Code     staticpublicvoidmain (String[] args)     {         intn = 3;         System.out.println(findSum(n));     } }  // This code is contributed by vt_m.  | 
Python3
| # Python 3 program to find sum of matrix  # in which each element is absolute  # difference of its corresponding row  # and column number row.   # Return the sum of matrix in which  # each element is absolute difference  # of its corresponding row and column  # number row  deffindSum(n):     n -=1    sum=0    sum+=(n *(n +1)) /2    sum+=(n *(n +1) *(2*n +1)) /6    returnint(sum)   # Driver Code n =3print(findSum(n))   # This code contributed by Rajput-Ji  | 
C#
| // C# program to find sum of matrix in which // each element is absolute difference of its // corresponding row and column number row. usingSystem;  publicclassGFG {      // Return the sum of matrix in which each element // is absolute difference of its corresponding // row and column number row staticintfindSum(intn) {     n--;     intsum = 0;     sum += (n * (n + 1)) / 2;     sum += (n * (n + 1) * (2 * n + 1)) / 6;     returnsum; }      // Driver Code     staticpublicvoidMain(String[] args)     {         intn = 3;         Console.WriteLine(findSum(n));     } }  // This code is contributed by vt_m.  | 
PHP
| <?php // PHP program to find sum of  // matrix in which each element  // is absolute difference of its  // corresponding row and column  // number row.  // Return the sum of matrix in  // which each element is absolute  // difference of its corresponding // row and column number row functionfindSum($n) {     $n--;     $sum= 0;     $sum+= ($n* ($n+ 1)) / 2;     $sum+= ($n* ($n+ 1) *                    (2 * $n+ 1)) / 6;     return$sum; }  // Driver Code $n= 3; echofindSum($n) ;  // This code is contributed // by nitin mittal.  ?>  | 
Javascript
| <script>  // Java script program to find sum of matrix in which // each element is absolute difference of its // corresponding row and column number row.      // Return the sum of matrix in which each element // is absolute difference of its corresponding // row and column number row functionfindSum( n) {     n--;     let sum = 0;     sum += (n * (n + 1)) / 2;     sum += (n * (n + 1) * (2 * n + 1)) / 6;     returnsum; }      // Driver Code    let n = 3;        document.write(findSum(n));     // This code is contributed by mohan pavan  </script> | 
8
Time Complexity: O(1), as we are not using any loops.
Auxiliary Space: O(1), as we are not using any extra space.
This article is contributed by
Anuj Chauhan. If you like neveropen and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the neveropen main page and help other Geeks. 
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!


 
                                    







