Python bootcamp · Lab 30

Greatest common divisor

mediumFunctions12 minLesson: Functions

Read the question, write Python on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Read two positive integers and print their greatest common divisor.

Euclid's algorithm: gcd(a, b) = gcd(b, a % b), and gcd(a, 0) = a.

Input. Two lines, each one positive integer.

Output. One integer: gcd(a, b).

Constraints

  • 1 ≤ a, b ≤ 1,000,000

Examples

Example 1
Input
48
18
Output
6
Example 2 — Coprime numbers share only 1.
Input
7
13
Output
1
Hint
  1. math.gcd(a, b) is built in — or write the while-loop version.
  2. while b: a, b = b, a % b; then print a.
Show correct code

Peek only after you have tried. You can still Check your own version.

import math
a = int(input())
b = int(input())
print(math.gcd(a, b))
main.pyPython · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.