classSolution: defsubarrayLCM(self, nums: List[int], k: int) -> int: ans, n = 0, len(nums) for i inrange(n): res = 1 for j inrange(i, n): res = lcm(res, nums[j]) if k % res: break# 剪枝:LCM 必须是 k 的因子 if res == k: ans += 1 return ans
funcsubarrayLCM(nums []int, k int) (ans int) { for i := range nums { lcm := 1 for _, x := range nums[i:] { lcm = lcm / gcd(lcm, x) * x if k%lcm > 0 { // 剪枝:lcm 必须是 k 的因子 break } if lcm == k { ans++ } } } return }
funcgcd(a, b int)int { for a != 0 { a, b = b%a, a } return b }
classSolution: defsubarrayLCM(self, nums: List[int], k: int) -> int: ans = 0 a = [] # [LCM,相同 LCM 区间的右端点] i0 = -1 for i, x inenumerate(nums): if k % x: # 保证后续求的 LCM 都是 k 的因子 a = [] i0 = i continue a.append([x, i]) # 原地去重,因为相同的 LCM 都相邻在一起 j = 0 for p in a: p[0] = lcm(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: ans += a[0][1] - i0 return ans
funcsubarrayLCM(nums []int, k int) (ans int) { type result struct{ lcm, i int } var a []result i0 := -1 for i, x := range nums { if k%x > 0 { a = nil i0 = i continue } for j, p := range a { a[j].lcm = p.lcm / gcd(p.lcm, x) * x } a = append(a, result{x, i}) j := 0 for _, q := range a[1:] { if a[j].lcm != q.lcm { j++ a[j] = q } else { a[j].i = q.i } } a = a[:j+1] if a[0].lcm == k { ans += a[0].i - i0 } } return }
funcgcd(a, b int)int { for a != 0 { a, b = b%a, a } return b }