On a quick implementation of GCD - Greatest Common Divisor - Part II
Another example that requires a quick GCD implementation, back from Euclidian days. Despite the nested loops yielding an N^2 complexity, in addition to the LogN GCD (hence a time complexity of N^2 * LogN), N is relatively small (10^3) leading to a reasonable execution time. Code is below, cheers, ACC. Number of Subarrays With GCD Equal to K - LeetCode 2447. Number of Subarrays With GCD Equal to K Medium 97 31 Add to List Share 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. Example 1: Input: nums = [9,3,1,2,6,3], k = 3 Output: 4 Explanation: The subarrays of nums where 3 is the greatest common divisor of all the subarray's elements are: - [9, 3 ,1,2,6,3] - [9,3,1,2,6, 3 ] - [ 9