Given an integer N, the task is to construct a matrix of size N2 using positive and negative integers and excluding 0, such that the sum of the matrix is equal to the sum of the diagonal of the matrix.
Input: N = 2
Diagonal sum = (1 + 4) = 5
Matrix sum = (1 – 2 + 2 + 4) = 5
Input: N = 5
1 2 3 5 10
3 1 4 -9 1
-19 6 1 5 -8
4 -7 2 1 12
-17 1 1 1 1
Diagonal sum = (1 + 1 + 1 + 1 + 1) = 5
Matrix sum = 5
The approach to solving the problem is to traverse all indices of the matrix and print a positive element(say y) at the N diagonal positions and equally distribute a single-valued positive and negative integer(say x and -x) in the remaining N2 – N positions.
Below is the implementation of the above approach:
1 2 -2 2 -2 2 1 -2 2 -2 2 -2 1 2 -2 2 -2 2 1 -2 2 -2 2 -2 1
Time Complexity: O(N2)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Filling diagonal to make the sum of every row, column and diagonal equal of 3x3 matrix
- Program to swap upper diagonal elements with lower diagonal elements of matrix.
- Construct a square Matrix whose parity of diagonal sum is same as size of matrix
- Length of a Diagonal of a Parallelogram using the length of Sides and the other Diagonal
- Construct an Array of size N in which sum of odd elements is equal to sum of even elements
- Generate a matrix having sum of secondary diagonal equal to a perfect square
- Program to check diagonal matrix and scalar matrix
- Program to convert given Matrix to a Diagonal Matrix
- Find the sum of the diagonal elements of the given N X N spiral matrix
- Sum of main diagonal elements in a Matrix which are prime
- Squares of Matrix Diagonal Elements
- Reverse Diagonal elements of matrix
- Program to convert the diagonal elements of the matrix to 0
- Print all the sub diagonal elements of the given square matrix
- Print all the super diagonal elements of the given square matrix
- Program to find the Product of diagonal elements of a matrix
- Check if two elements of a matrix are on the same diagonal or not
- Circular Matrix (Construct a matrix with numbers 1 to m*n in spiral way)
- Construct a Matrix with no element exceeding X and sum of two adjacent elements not exceeding Y
- Sum of non-diagonal parts of a square Matrix
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.