Given an integer array nums and an integer k, return _the number ofsubarrays of _nums _where the least common multiple of the subarray ’s elements is _k.
A subarray is a contiguous non-empty sequence of elements within an array.
The least common multiple of an array is the smallest positive integer that is divisible by all the array elements.
Input: nums =[3,6,2,7,1], k =6Output: 4Explanation: The subarrays of nums where 6is the least common multiple of all the subarray's elements are:-[_**3**_ ,_**6**_ ,2,7,1]-[_**3**_ ,_**6**_ ,_**2**_ ,7,1]-[3,_**6**_ ,2,7,1]-[3,_**6**_ ,_**2**_ ,7,1]
classSolution {
publicintsubarrayLCM(int[] nums, int k) {
int n = nums.length, ans = 0;
for (int i = 0; i < n; i++) {
int lcm = 1;
for (int j = i; j < n; j++) {
lcm = lcm(lcm, nums[j]);
if (lcm == k) ans++;
if (lcm > k) break;
}
}
return ans;
}
privateintlcm(int a, int b) {
return a / gcd(a, b) * b;
}
privateintgcd(int a, int b) {
while (b != 0) {
int t = b; b = a % b; a = t;
}
return a;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
funsubarrayLCM(nums: IntArray, k: Int): Int {
fungcd(a: Int, b: Int): Int = if (b ==0) a else gcd(b, a % b)
funlcm(a: Int, b: Int): Int = a / gcd(a, b) * b
var ans = 0for (i in nums.indices) {
var l = 1for (j in i until nums.size) {
l = lcm(l, nums[j])
if (l == k) ans++if (l > k) break }
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from math import gcd
classSolution:
defsubarrayLCM(self, nums: list[int], k: int) -> int:
deflcm(a, b):
return a * b // gcd(a, b)
n, ans = len(nums), 0for i in range(n):
l =1for j in range(i, n):
l = lcm(l, nums[j])
if l == k:
ans +=1if l > k:
breakreturn ans
impl Solution {
pubfnsubarray_lcm(nums: Vec<i32>, k: i32) -> i32 {
fngcd(mut a: i32, mut b: i32) -> i32 {
while b !=0 {
let t = b; b = a % b; a = t;
}
a
}
fnlcm(a: i32, b: i32) -> i32 {
a / gcd(a, b) * b
}
let n = nums.len();
letmut ans =0;
for i in0..n {
letmut l =1;
for j in i..n {
l = lcm(l, nums[j]);
if l == k { ans +=1; }
if l > k { break; }
}
}
ans
}
}