Replace every matrix element with maximum of GCD of row or column
Last Updated :
05 May, 2023
Given a matrix of n rows and m columns. The task is to replace each matrix element with Greatest Common Divisor of its row or column, whichever is maximum. That is, for each element (i, j) replace it from GCD of i'th row or GCD of j'th row, whichever is greater.
Examples :
Input : mat[3][4] = {1, 2, 3, 3,
4, 5, 6, 6
7, 8, 9, 9}
Output : 1 1 3 3
1 1 3 3
1 1 3 3
For index (0,2), GCD of row 0 is 1, GCD of row 2 is 3.
So replace index (0,2) with 3 (3>1).
The idea is to us concept discussed here LCM of an array to find the GCD of row and column.
Using the brute force, we can traverse element of matrix, find the GCD of row and column corresponding to the element and replace it with maximum of both.
An Efficient method is to make two arrays of size n and m for row and column respectively. And store the GCD of each row and each column. An Array of size n will contain GCD of each row and array of size m will contain the GCD of each column. And replace each element with maximum of its corresponding row GCD or column GCD.
Below is the implementation of this approach:
C++
// C++ program to replace each element with
// maximum of GCD of row or column.
#include<bits/stdc++.h>
using namespace std;
#define R 3
#define C 4
// returning the greatest common divisor of two number
int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a%b);
}
// Finding GCD of each row and column and replacing
// with each element with maximum of GCD of row or
// column.
void replacematrix(int mat[R][C], int n, int m)
{
int rgcd[R] = { 0 }, cgcd[C] = { 0 };
// Calculating GCD of each row and each column in
// O(mn) and store in arrays.
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
rgcd[i] = gcd(rgcd[i], mat[i][j]);
cgcd[j] = gcd(cgcd[j], mat[i][j]);
}
}
// Replacing matrix element
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
mat[i][j] = max(rgcd[i], cgcd[j]);
}
// Driven Program
int main()
{
int m[R][C] =
{
1, 2, 3, 3,
4, 5, 6, 6,
7, 8, 9, 9,
};
replacematrix(m, R, C);
for (int i = 0; i < R; i++)
{
for (int j = 0; j < C; j++)
cout << m[i][j] << " ";
cout<<endl;
}
return 0;
}
Java
// Java program to replace each element with
// maximum of GCD of row or column.
import java .io.*;
class GFG
{
static int R = 3;
static int C = 4;
// returning the greatest common
// divisor of two number
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a%b);
}
// Finding GCD of each row and column and
// replacing with each element with maximum
// of GCD of row or column.
static void replacematrix(int [][]mat, int n, int m)
{
int []rgcd = new int[R] ;
int []cgcd = new int[C];
// Calculating GCD of each row and each column in
// O(mn) and store in arrays.
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
rgcd[i] = gcd(rgcd[i], mat[i][j]);
cgcd[j] = gcd(cgcd[j], mat[i][j]);
}
}
// Replacing matrix element
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
mat[i][j] = Math.max(rgcd[i], cgcd[j]);
}
// Driver program
static public void main (String[] args){
int [][]m =
{
{1, 2, 3, 3},
{4, 5, 6, 6},
{7, 8, 9, 9},
};
replacematrix(m, R, C);
for (int i = 0; i < R; i++)
{
for (int j = 0; j < C; j++)
System.out.print(m[i][j] + " ");
System.out.println();
}
}
}
//This code is contributed by vt_m.
Python3
# Python3 program to replace each element
# with maximum of GCD of row or column.
R = 3
C = 4
# returning the greatest common
# divisor of two number
def gcd(a, b):
if (b == 0):
return a
return gcd(b, a % b)
# Finding GCD of each row and column
# and replacing with each element with
# maximum of GCD of row or column.
def replacematrix(mat, n, m):
rgcd = [0] * R
cgcd = [0] * C
# Calculating GCD of each row and each
# column in O(mn) and store in arrays.
for i in range (n):
for j in range (m):
rgcd[i] = gcd(rgcd[i], mat[i][j])
cgcd[j] = gcd(cgcd[j], mat[i][j])
# Replacing matrix element
for i in range (n):
for j in range (m):
mat[i][j] = max(rgcd[i], cgcd[j])
# Driver Code
if __name__ == "__main__":
m = [[1, 2, 3, 3],
[4, 5, 6, 6],
[7, 8, 9, 9]]
replacematrix(m, R, C)
for i in range(R):
for j in range (C):
print ( m[i][j], end = " ")
print ()
# This code is contributed by ita_c
C#
// C# program to replace each element with
// maximum of GCD of row or column.
using System;
class GFG
{
static int R = 3;
static int C = 4;
// returning the greatest common
// divisor of two number
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a%b);
}
// Finding GCD of each row and column and
// replacing with each element with maximum
// of GCD of row or column.
static void replacematrix(int [,]mat, int n, int m)
{
int []rgcd = new int[R] ;
int []cgcd = new int[C];
// Calculating GCD of each row and each column in
// O(mn) and store in arrays.
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
rgcd[i] = gcd(rgcd[i], mat[i,j]);
cgcd[j] = gcd(cgcd[j], mat[i,j]);
}
}
// Replacing matrix element
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
mat[i,j] = Math.Max(rgcd[i], cgcd[j]);
}
// Driver program
static public void Main (){
int [,]m =
{
{1, 2, 3, 3},
{4, 5, 6, 6},
{7, 8, 9, 9},
};
replacematrix(m, R, C);
for (int i = 0; i < R; i++)
{
for (int j = 0; j < C; j++)
Console.Write(m[i,j] + " ");
Console.WriteLine();
}
}
}
//This code is contributed by vt_m.
JavaScript
<script>
// Javascript program to replace each element with
// maximum of GCD of row or column.
let R = 3;
let C = 4;
// returning the greatest common
// divisor of two number
function gcd(a, b)
{
if (b == 0)
return a;
return gcd(b, a%b);
}
// Finding GCD of each row and column and
// replacing with each element with maximum
// of GCD of row or column.
function replacematrix(mat, n, m)
{
let rgcd = new Array(R);
rgcd.fill(0);
let cgcd = new Array(C);
cgcd.fill(0);
// Calculating GCD of each row and each column in
// O(mn) and store in arrays.
for (let i = 0; i < n; i++)
{
for (let j = 0; j < m; j++)
{
rgcd[i] = gcd(rgcd[i], mat[i][j]);
cgcd[j] = gcd(cgcd[j], mat[i][j]);
}
}
// Replacing matrix element
for (let i = 0; i < n; i++)
for (let j = 0; j < m; j++)
mat[i][j] = Math.max(rgcd[i], cgcd[j]);
}
let m = [ [1, 2, 3, 3],
[4, 5, 6, 6],
[7, 8, 9, 9] ];
replacematrix(m, R, C);
for (let i = 0; i < R; i++)
{
for (let j = 0; j < C; j++)
document.write(m[i][j] + " ");
document.write("</br>");
}
</script>
Output1 1 3 3
1 1 3 3
1 1 3 3
Time Complexity : O(mn).
Auxiliary Space : O(m + n). Since m + n extra space has been taken.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read