<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the number of <strong>subarrays</strong> of </em><code>nums</code><em> where the greatest common divisor of the subarray&#39;s elements is </em><code>k</code>.</p>

<p>A <strong>subarray</strong> is a contiguous non-empty sequence of elements within an array.</p>

<p>The <strong>greatest common divisor of an array</strong> is the largest integer that evenly divides all the array elements.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [9,3,1,2,6,3], k = 3
<strong>Output:</strong> 4
<strong>Explanation:</strong> The subarrays of nums where 3 is the greatest common divisor of all the subarray&#39;s elements are:
- [9,<u><strong>3</strong></u>,1,2,6,3]
- [9,3,1,2,6,<u><strong>3</strong></u>]
- [<u><strong>9,3</strong></u>,1,2,6,3]
- [9,3,1,2,<u><strong>6,3</strong></u>]
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [4], k = 7
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are no subarrays of nums where 7 is the greatest common divisor of all the subarray&#39;s elements.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 1000</code></li>
	<li><code>1 &lt;= nums[i], k &lt;= 10<sup>9</sup></code></li>
</ul>

class Solution:
    def subarrayGCD(self, nums: List[int], k: int) -> int:
        
        # Basic GCD code.
        def GCD(a, b):
            if a < b: return GCD(b, a)
            if b == 0: return a 
            if a % b == 0: return b 
            return GCD(b, a % b)

        # Treating nums[0] separately.
        res, prevH = 0, collections.defaultdict(int)
        if nums[0] == k: res += 1
        prevH[nums[0]] += 1

        for i in range(1, len(nums)):
            # The gcd of nums[i] is nums[i], so we add this gcd into
            # prevH just to account for the edge-case where nums[i] == k
            H = collections.defaultdict(int)
            prevH[nums[i]] += 1

            # The use of dict(prevH) is just a Python workaround
            # (feel free to ignore).
            for prev_gcd, freq in dict(prevH).items():
                # If we considered this subarray, what would be the gcd of the subarray?
                gcd = GCD(prev_gcd, nums[i])

                if gcd == k:
                    # There are 'freq' number of subarrays that correspond to this gcd.
                    res += freq
                H[gcd] += freq
            prevH = H 
        return res
57