Find Consecutive Elements in a Matrix with GCD Greater than 1 in Python



Suppose we are given a matrix that contains n rows and m columns. We have to find out the largest number of consecutive elements in the matrix where the gcd of the elements is greater than 1. The consecutive elements can either lie horizontally or vertically in the matrix.

So, if the input is like

3 7 9 12
5 9 4 6
7 8 5 10

and m = 4, n = 3; then the output will be 3.

The fourth column of the given matrix is 12, 6, 10. The gcd of the elements of this column is 2. As there are three elements, the answer is 3.

To solve this, we will follow these steps −

  • mat := a new 3d list of dimensions m x n x n
  • res := 0
    • for i in range 0 to n, do
      • for j in range i to n, do
        • gcd_temp := 0
        • x := 0
        • for k in range 0 to m, do
          • if i is same as j, then
            • mat[i, j, k] := input_list[i, k]
          • otherwise,
            • mat[i, j, k] = gcd of elements(mat[i, j-1, k], input_list[j, k])
          • gcd_temp = gcd of elements (gcd_temp, mat[i, j, k])
          • if gcd_temp > 1, then
            • x := x + j - i + 1
          • otherwise,
            • res := maximum of res, x
            • if mat[i, j, k] > 1, then
              • gcd_temp := mat[i, j, k]
              • x := j - i + 1
    • res := maximum of res, x
  • return res

Example

Let us see the following implementation to get better understanding −

from math import gcd
def solve(n, m, input_list):
   mat = [[[0] *m] *n] *n
   res = 0
   for i in range(n):
      for j in range(i, n):
         gcd_temp = 0
         x = 0
         for k in range(m):
            if i == j:
               mat[i][j][k] = input_list[i][k]
            else:
               mat[i][j][k] = gcd(mat[i][j-1][k], input_list[j][k])
gcd_temp = gcd(gcd_temp, mat[i][j][k])
if gcd_temp > 1:
x += j - i + 1
else:
res = max(res,x)
if mat[i][j][k] > 1:
gcd_temp = mat[i][j][k]
x = j - i + 1
res = max(res,x)
return res
print(solve(3, 4, [[3, 7, 9, 12], [5, 9, 4, 6], [7, 8, 5, 10]]))

Input

3, 4, [[3, 7, 9, 12], [5, 9, 4, 6], [7, 8, 5, 10]]

Output

3
Updated on: 2021-10-20T07:43:46+05:30

186 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements