Find a Square Matrix such that sum of elements in every row and column is K
Given two integers N and K, the task is to find an N x N square matrix such that sum of every row and column should be equal to K. Note that there can be multiple such matrices possible. Print any one of them.
Examples:
Input: N = 3, K = 15
Output:
2 7 6
9 5 1
4 3 8
Input: N = 3, K = 7
Output:
7 0 0
0 7 0
0 0 7
Approach: An N x N matrix such that each left diagonal element is equal to K and rest elements are 0 will satisfy the given condition. In this way, the sum of the elements of the each row and column will be equal to K.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void printMatrix( int n, int k)
{
for ( int i = 0; i < n; i++) {
for ( int j = 0; j < n; j++) {
if (i == j)
cout << k << " " ;
else
cout << "0 " ;
}
cout << "\n" ;
}
}
int main()
{
int n = 3, k = 7;
printMatrix(n, k);
return (0);
}
|
Java
import java.util.*;
class GFG
{
static void printMatrix( int n, int k)
{
for ( int i = 0 ; i < n; i++)
{
for ( int j = 0 ; j < n; j++)
{
if (i == j)
System.out.print(k + " " );
else
System.out.print( "0 " );
}
System.out.print( "\n" );
}
}
public static void main(String[] args)
{
int n = 3 , k = 7 ;
printMatrix(n, k);
}
}
|
Python3
def printMatrix(n, k) :
for i in range (n) :
for j in range (n) :
if (i = = j) :
print (k, end = " " );
else :
print ( "0" , end = " " );
print ();
if __name__ = = "__main__" :
n = 3 ; k = 7 ;
printMatrix(n, k);
|
C#
using System;
class GFG
{
static void printMatrix( int n, int k)
{
for ( int i = 0; i < n; i++)
{
for ( int j = 0; j < n; j++)
{
if (i == j)
Console.Write(k + " " );
else
Console.Write( "0 " );
}
Console.Write( "\n" );
}
}
public static void Main(String[] args)
{
int n = 3, k = 7;
printMatrix(n, k);
}
}
|
Javascript
<script>
function printMatrix(n , k)
{
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if (i == j)
document.write(k + " " );
else
document.write( "0 " );
}
document.write( "</br>" );
}
}
var n = 3, k = 7;
printMatrix(n, k);
</script>
|
Output:
7 0 0
0 7 0
0 0 7
Time Complexity: O(N*N), as we are using nested loops to traverse N*N times.
Auxiliary Space: O(1), as we are not using any extra space.
Last Updated :
30 May, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...