#2447
Medium Algorithms Number of subarrays with gcd equal to k
Array Math Number Theory
52.4% acceptance
Feb 25, 2026
463
71
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 di
vides all the array elements. *
Solution
Rust
Time O(n²)
Space O(n)
impl Solution {
pub fn subarray_gcd(nums: Vec<i32>, k: i32) -> i32 {
fn gcd(a: i32, b: i32) -> i32 { if b == 0 { a } else { gcd(b, a % b) } }
let n = nums.len();
let mut count = 0;
for i in 0..n {
let mut g = 0;
for j in i..n {
g = gcd(g, nums[j]);
if g == k { count += 1; }
if g < k { break; }
}
}
count
}
}