classSolution: defsubarrayGCD(self, nums: List[int], k: int) -> int: ans = 0 for i inrange(len(nums)): g = 0 for j inrange(i, len(nums)): g = gcd(g, nums[j]) if g % k: break if g == k: ans += 1 return ans
funcsubarrayGCD(nums []int, k int) (ans int) { for i := range nums { g := 0 for _, x := range nums[i:] { g = gcd(g, x) if g%k > 0 { break } if g == k { ans++ } } } return }
funcgcd(a, b int)int { for a != 0 { a, b = b%a, a } return b }
classSolution: defsubarrayGCD(self, nums: List[int], k: int) -> int: ans = 0 a = [] # [GCD,相同 GCD 区间的右端点] i0 = -1 for i, x inenumerate(nums): if x % k: # 保证后续求的 GCD 都是 k 的倍数 a = [] i0 = i continue a.append([x, i]) # 原地去重,因为相同的 GCD 都相邻在一起 j = 0 for p in a: p[0] = gcd(p[0], x) if a[j][0] != p[0]: j += 1 a[j] = p else: a[j][1] = p[1] del a[j + 1:] if a[0][0] == k: # a[0][0] >= k ans += a[0][1] - i0 return ans
funcsubarrayGCD(nums []int, k int) (ans int) { type result struct{ v, i int } var a []result i0 := -1 for i, v := range nums { if v%k > 0 { a = nil i0 = i continue } for j, p := range a { a[j].v = gcd(p.v, v) } a = append(a, result{v, i}) j := 0 for _, q := range a[1:] { if a[j].v != q.v { j++ a[j] = q } else { a[j].i = q.i } } a = a[:j+1] if a[0].v == k { ans += a[0].i - i0 } } return }
funcgcd(a, b int)int { for a != 0 { a, b = b%a, a } return b }