Python Nozioni di baseFacile

Massimo Comun Divisore

Guida dettagliata e implementazione Python per il problema del "massimo comun divisore".

Dichiarazione del problema

Facile

Scrivi una funzione gcd(a, b) che accetta due interi non negativi a e b (non entrambi zero) e restituisce il loro massimo comune divisore (GCD) utilizzando l'algoritmo euclideo. Il GCD è il numero più grande che divide sia a che b.

L'algoritmo euclideo funziona sostituendo ripetutamente il numero più grande con il resto della divisione del più grande per il più piccolo, fino a quando il resto è 0. L'ultimo resto diverso da zero è il MCD.

Vincoli
  • 0 <= a, b <= 10^6
  • a and b are not both zero

Esempi

Example 1
Input
gcd(48, 18)
Output
6
Explanation

48 % 18 = 12, then 18 % 12 = 6, then 12 % 6 = 0. So GCD is 6.

Example 2
Input
gcd(56, 98)
Output
14
Explanation

98 % 56 = 42, 56 % 42 = 14, 42 % 14 = 0. So GCD is 14.

Example 3
Input
gcd(0, 5)
Output
5
Explanation

GCD(0, n) = n for any positive n.

Need a Hint?
Prendi in considerazione l'utilizzo di strutture dati specifiche di Numbers come set o heap.
Edge Cases to Watch
  • Strutture di input vuote
  • Ingressi a elemento singolo
  • Grandi limiti numerici

Pronto a risolvere?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Apri nell'editor
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

Risorse Python consigliate

Espandi le tue conoscenze con tutorial interattivi, foglietti illustrativi e confronti di codici correlati.