Skip to the content

The divisor that fits them all

Problem

A divisor of a number is another number that fits into it with nothing left over: 3 is a divisor of 12, because 12 divided by 3 is exactly 4. Write a function that takes a list of numbers and returns the biggest divisor that fits all of them at once.

With 12, 18 and 30 the answer is 6: all three split into pieces of 6 with nothing left over, and no bigger number manages that.

The rules: the numbers are never negative. With a single number, that same number is the answer, because it fits into itself. Zero can be divided by any number with nothing left over, so it does not call the shots: with 0, 9 and 15 the answer is 3. If the list comes in empty, you return 0. And careful, it is not always the smallest number: with 8, 24 and 12 the answer is 4, not 8.

There are two roads. One: try candidates from big to small until one divides them all. The other: drag the answer along the list, because the common divisor of the whole list is the common divisor of what you carry so far and the next number.

Examples

  • All even

    [2, 4, 6, 8, 16] → 2

  • Nothing in common

    [1, 2, 3] → 1

  • Twelve, eighteen and thirty

    [12, 18, 30] → 6

  • Not the smallest one

    [8, 24, 12] → 4

Besides these, the challenge has hidden tests that are revealed when you submit your solution.

You start with this

Python

def common_divisor(numbers):
    pass

JavaScript

function commonDivisor(numbers) {
}
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(n) challenges

See all challenges →