Skip to content

4069. Count Ways To Choose Coprime Integers From Rows


4069. Count Ways to Choose Coprime Integers from Rows

Hard


You are given a m x n matrix mat of positive integers.

Return an integer denoting the number of ways to choose exactly one integer from each row of mat such that the greatest common divisor of all chosen integers is 1.

Since the answer may be very large, return it modulo 109 + 7.

 

Example 1:

Input: mat = [[1,2],[3,4]]

Output: 3

Explanation:

Chosen integer in the first row Chosen integer in the second row Greatest common divisor of chosen integers
1 3 1
1 4 1
2 3 1
2 4 2

3 of these combinations have a greatest common divisor of 1. Therefore, the answer is 3.

Example 2:

Input: mat = [[2,2],[2,2]]

Output: 0

Explanation:

Every combination has a greatest common divisor of 2. Therefore, the answer is 0.

 

Constraints:

  • 1 <= m == mat.length <= 150
  • 1 <= n == mat[i].length <= 150
  • 1 <= mat[i][j] <= 150

Solution

class Solution {
    private int mod = (int)(1e9 + 7);
    private int dp[][];
    public int countCoprime(int[][] mat) {
        int n = mat.length, m = mat[0].length;
        dp = new int[n + 1][200];
        for (int current[] : dp)
            Arrays.fill(current, -1);
        return solve(0, 0, mat);
    }
    private int solve(int currRow, int gcd, int arr[][]) {
        if (currRow >= arr.length) {
            if (gcd == 1)
                return 1;
            return 0;
        }
        if (dp[currRow][gcd] != -1)
            return dp[currRow][gcd];
        int ans = 0;
        for (int j = 0; j < arr[0].length; j++) {
            int op1 = solve(currRow + 1, GCD(gcd, arr[currRow][j]), arr);
            ans = (ans + op1) % mod;
        }
        return dp[currRow][gcd] = ans;
    }
    private int GCD(int a, int b) {
        if (a == 0)
            return b;
        if (b == 0) 
            return a;
        while (b != 0) {
            int temp = b;
            b = a % b;
            a = temp;
        }
        return a;
    }
}

Complexity Analysis

  • Time Complexity: O(?)
  • Space Complexity: O(?)

Explanation

[Add detailed explanation here]