[LeetCode] Number of Subarrays With GCD Equal to K

2447. Number of Subarrays With GCD Equal to K

Given an integer array nums and an integer k, return the number of subarrays 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int subarrayGCD(vector<int>& nums, int k) {
int res = 0;
for(int i = 0; i < nums.size(); i++) {
int g = nums[i];
if(g == k) res += 1;
for(int j = i + 1; j < nums.size() and g % k == 0; j++) {
g = __gcd(g,nums[j]);
if(g == k) res += 1;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/02/08/PS/LeetCode/number-of-subarrays-with-gcd-equal-to-k/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.