[UCSD白板题] Greatest Common Divisor

时间:2021-09-30 09:53:26

Problem Introduction

The greatest common divisor \(GCD(a, b)\) of two non-negative integers \(a\) and \(b\) (which are not both equal to 0) is the greatest integer \(d\) that divides both \(a\) and \(b\).

Problem Description

Task.Given two integer \(a\) and \(b\), find their greatest common divisor.

Input Format.The two integers \(a\),\(b\) are given in the same line separated by space.

Constraints. \(1 \leq a, b \leq 2 \cdot 10^9\).

Output Format. Output \(GCD(a,b)\).

Sample 1.
Input:

18 35

Output:

1

Sample 2.
Input:

28851538 1183019

Output:

17657

Solution

# Uses python3
import sys

def gcd(a, b):
    if b == 0:
        return a
    return gcd(b, a % b)

if __name__ == "__main__":
    input = sys.stdin.read()
    a, b = map(int, input.split())
    print(gcd(a, b))