Torna alle sfide
Facile 0 risolte 0% di accettazione

Greatest Common Divisor

Find the largest number that divides both values.

Cosa imparerai

  • Apply Euclid's algorithm with remainders
  • Turn a math rule into a loop
  • Understand why the algorithm is fast

Problema

Mostra traduzione

Return the greatest common divisor of a and b. Euclid's algorithm repeatedly replaces (a, b) with (b, a mod b) until b is 0.

Implement gcd(a, b).

Input

a: The first number. b: The second number.

Output

Return gcd(a, b). gcd(0, 0) is 0.

Vincoli

0 ≤ a, b ≤ 10¹⁸

Esempi

Esempio 1
Input:
a = 48
b = 18

Output atteso:
expected = 6
Input:
long long a = 48;
long long b = 18;

Output atteso:
long long expected = 6;
Input:
long a = 48;
long b = 18;

Output atteso:
long expected = 6;

Spiegazione

48 mod 18 = 12, 18 mod 12 = 6, 12 mod 6 = 0, so the answer is 6.

Esempio 2
Input:
a = 17
b = 5

Output atteso:
expected = 1
Input:
long long a = 17;
long long b = 5;

Output atteso:
long long expected = 1;
Input:
long a = 17;
long b = 5;

Output atteso:
long expected = 1;

Spiegazione

17 and 5 share no factor other than 1.

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

The gcd does not change when you replace a pair with the remainder step.

Suggerimento 2

Keep swapping the roles of the two numbers until the second becomes zero.

Suggerimento 3

Be sure to handle the case where both inputs are zero.

Complessità attesa

O(log min(a, b)) time, O(1) extra space

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.