Implement the gcdArrayValues method that returns the greatest common divisor of all array values.

The input contains an integer array nums and its length size. Your task is to return the greatest common divisor of all values in the array.

The greatest common divisor is the largest positive number that divides every value without a remainder. For example, the GCD of [12,18,24] is 6.

Example 1

Input
nums (int[]) = [12,18,24]
size (int) = 3
Returns (int) 6

Example 2

Input
nums (int[]) = [8,12,16]
size (int) = 3
Returns (int) 4

Example 3

Input
nums (int[]) = [7,13]
size (int) = 2
Returns (int) 1

Use the Euclidean algorithm to calculate the GCD of two numbers, then apply it across the full array.

Start with the first array value as the current GCD. For each next value, replace the current GCD with the GCD of the current result and that value.

After all numbers are processed, the remaining value is the GCD of the complete array.

Pseudocode:

function gcd(a, b):
    while b != 0:
        remainder = a % b
        a = b
        b = remainder
    return absolute value of a
function gcdArrayValues(nums, size):
    result = nums[0]
    for i from 1 to size - 1:
        result = gcd(result, nums[i])
    return result
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.