N
N
Natalia Veis2022-01-27 19:13:14
Python
Natalia Veis, 2022-01-27 19:13:14

Euclid's algorithm?

I've been sitting all day and can't understand how the program is executed by the code. Finding the greatest common divisor.
Here is the code

Def gcd(a, b) :
    return a If b==0 else gcd(b, a%b)

What is not clear: in case - а<bhow will it work.?
For example
gcd(243,456)
Will it do - (456, 243%456)?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexandroppolus, 2022-01-27
@Nalali98

if a < b then a%b is always equal to a

A
Alexander Skusnov, 2022-01-27
@AlexSku

Yes. In the first step, a and b are swapped (i.e. the next call will be gcd(456, 243), so a is always greater than b until b is 0.

B
bbkmzzzz, 2022-01-27
@bbkmzzzz

Def gcd(a, b) :
    return a If b==0 else gcd(b, a%b)
# эквивалентно
def gcd(a,b):
    if b == 0:
        return a
    else:
        #вызываем сами себя (рекурсия)
        gcd(b, a % b)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question