Given an integer array nums and an integer k, return _the number ofsubarrays of _nums _where the greatest common divisor of the subarray ’s elements is _k.
A subarray is a contiguous non-empty sequence of elements within an array.
The greatest common divisor of an array is the largest integer that evenly divides all the array elements.
Input: nums =[9,3,1,2,6,3], k =3Output: 4Explanation: The subarrays of nums where 3is the greatest common divisor of all the subarray's elements are:-[9,_**3**_ ,1,2,6,3]-[9,3,1,2,6,_**3**_]-[_**9,3**_ ,1,2,6,3]-[9,3,1,2,_**6,3**_]
#include<numeric>classSolution {
public:int subarrayGCD(vector<int>& nums, int k) {
int n = nums.size(), ans =0;
for (int i =0; i < n; ++i) {
int g =0;
for (int j = i; j < n; ++j) {
g = std::gcd(g, nums[j]);
if (g == k) ans++;
if (g < k) break;
}
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
funcgcd(a, bint) int {
forb!=0 {
a, b = b, a%b }
returna}
funcsubarrayGCD(nums []int, kint) int {
n, ans:= len(nums), 0fori:=0; i < n; i++ {
g:=0forj:=i; j < n; j++ {
g = gcd(g, nums[j])
ifg==k { ans++ }
ifg < k { break }
}
}
returnans}
classSolution {
publicintsubarrayGCD(int[] nums, int k) {
int n = nums.length, ans = 0;
for (int i = 0; i < n; i++) {
int g = 0;
for (int j = i; j < n; j++) {
g = gcd(g, nums[j]);
if (g == k) ans++;
if (g < k) break;
}
}
return ans;
}
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
classSolution {
funsubarrayGCD(nums: IntArray, k: Int): Int {
fungcd(a: Int, b: Int): Int = if (b ==0) a else gcd(b, a % b)
var ans = 0for (i in nums.indices) {
var g = 0for (j in i until nums.size) {
g = gcd(g, nums[j])
if (g == k) ans++if (g < k) break }
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
from math import gcd
classSolution:
defsubarrayGCD(self, nums: list[int], k: int) -> int:
n, ans = len(nums), 0for i in range(n):
g =0for j in range(i, n):
g = gcd(g, nums[j])
if g == k:
ans +=1if g < k:
breakreturn ans
impl Solution {
pubfnsubarray_gcd(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
}
let n = nums.len();
letmut ans =0;
for i in0..n {
letmut g =0;
for j in i..n {
g = gcd(g, nums[j]);
if g == k { ans +=1; }
if g < k { break; }
}
}
ans
}
}