Five common methods for Python to find the greatest common divisor

Finding the greatest common divisor is a relatively common type of exercises. The following editor will provide you with five more common algorithms. Remember to give a thumbs up!

Generally speaking, there are about 5 ways to find the greatest common divisor

Method 1: Short division

        Short division is a method of finding the greatest common factor , and it can also be used to find the least common multiple . The method of finding the greatest common factor of several numbers starts with the method of observation and comparison, that is: first find out the factors of each number, then find out the common factor , and finally find out the greatest common factor among the common factors. Later, the method of decomposing prime factors was used to decompose the factors of the two numbers separately, and then perform operations. Then it evolved into short division. The operation method of short division is to first divide a divisor by a prime number that can be divided by it, and so on until the quotient of the two numbers is a co-prime number.

        To put it simply, it is to find out all the common divisors of two numbers step by step, and then multiply these common divisors together to get the greatest common divisor!

a=int(input("please input the first number:"))
b=int(input("please input the second number:"))
m,n=a,b #  创建两个变量存储a和b
t=1 #  创建t作为最大公约数的载体
for i in range(2,min(a,b)):
    while (a%i==0 and b%i==0):
       t*=i #  所有公约数累乘起来
       a/=i
       b/=i
print((f"{m},{n}的最大公约数为:{t}"))

        Although this method is a bit troublesome, the logic is very clear and it is not easy to make mistakes.

Method 2: Euclidean Algorithm (Rolling and Dividing Method)

        Euclid's algorithm is an algorithm for finding the greatest common divisor of two positive integers. The ancient Greek mathematician Euclid first described this algorithm in his book "The Elements", so it was named Euclid's algorithm.      

        If you need to find the greatest common divisor of two positive integers 1997 and 615, use the Euclidean algorithm to proceed as follows:

1997 / 615 = 3······152

615 / 152 = 4······7

152 / 7 = 21······5

7 / 5 = 1······2

5 / 2 = 2······1

2 / 1 = 2······0

        So far, the greatest common divisor is 1

        Repeat the division operation with the divisor and the remainder. When the remainder is 0, take the divisor of the current formula as the greatest common divisor, so the greatest common divisor 1 of 1997 and 615 is obtained.

        After understanding the logic, we can start writing programs!

a=int(input("please input the first number:"))
b=int(input("please input the second number:"))
#  首先要给两数排序,保证大数除以小数
m=max(a,b)
n=min(a,b)
t=m%n
while t!=0:
    m,n=n,t #  仔细观察不难发现:每个除式的m、n是都是上一个式子的n和余数
    t=m%n #  更新余数
print(f"{a}和{b}的最大公约数为{n}")

        Of course, recursive methods can also implement Euclid's algorithm.

def GCD(a,b):
    #  比较大小,保证大数除以小数
    if a<b:
        a,b=b,a
    #  判断是否能整除,若能整除,直接返回被除数
    if a%b==0:
        return b
    #  若不能整除,则返回函数GCD,参数做相应变化
    else:
        return GCD(b,a%b)
a=int(input("please input the first number:"))
b=int(input("please input the second number:"))
gcd=GCD(a,b)
print(f"{a}和{b}的最大公约数为{gcd}")

Method 3: Phase reduction surgery

        More phase subtraction is an algorithm for finding the greatest common divisor from " Nine Chapters of Arithmetic " . It was originally designed for reduction , but it is suitable for any occasion that requires the greatest common divisor. The original text is:

        If it can be half, it can be half, if it can't be half, set the denominator and the number of sons, reduce the number with the less, and reduce the loss, and seek the same. Approximate it by an equal number.     

Vernacular translation:

(If you need to divide the score, then) if it can be halved, then halve it (that is, use 2 to divide). If it cannot be halved, then compare the size of the denominator and the numerator, subtract the decimal from the large number, and subtract each other until the subtrahend and the difference are equal, and use this equal number to divide.

        Specific steps:

Step 1: Given any two positive integers; determine whether they are both even numbers. If yes, use 2 to reduce; if not, go to the second step.

Step 2: Subtract the smaller number by the larger number, then compare the resulting difference with the smaller number, and reduce the number by the larger number. Continue this operation until the resulting subtrahend and difference are equal.

Then the product of several products of 2 that were reduced in the first step and the average number in the second step is the greatest common divisor sought.

The "equal numbers" mentioned here are common divisors. The way to seek "equal numbers" is the method of "comparing the losses".

        Now use the phase reduction technique to find the greatest common divisor of 98 and 63 .

Solution: Since 63 is not an even number, reduce 98 and 63 with a large number and subtract them repeatedly :

98-63=35

63-35=28

35-28=7

28-7=21

21-7=14

14-7=7

Therefore, the greatest common divisor of 98 and 63 is equal to 7.

a=int(input("please input the first number:"))
b=int(input("please input the second number:"))
#  首先要给两数排序,保证大数减小数
m=max(a,b)
n=min(a,b)
#  判断两数是否都是偶数,如果都是偶数就同时除2
while m%2==0 and n%2==0:
    m,n=m/2,n/2
t=m-n
#  判断条件是减数和差相等
while n!=t:
    m,n=max(n,t),min(n,t) #  每减一轮之后,都要重新判断减数和差的大小,再次以大数减去小数
    t=m-n
print(f"{a}和{b}的最大公约数为{n}")

Method 4: Exhaustive method (enumeration method)

        Starting from the smaller number of the two numbers, enumerate from small to large, find the common divisor and ensure that the common divisor also belongs to the larger number, the largest of these common divisors is the greatest common divisor; you can also list from large to small, Jump out of the loop until the common divisor is found, and the common divisor is the greatest common divisor.

a=int(input("please input the first number:"))
b=int(input("please input the second number:"))
p,q=min(a,b),max(a,b)
lst=[]
for i in range(1,p+1):
    if p%i==0 and q%i==0:
        lst.append(i)
gcd=max(lst)
print(f"{a}和{b}的最大公约数为{gcd}")

#a=int(input("please input the first number:"))
#b=int(input("please input the second number:"))
#p,q=min(a,b),max(a,b)
#gcd=0
#for i in range(p,0,-1):
#    if p%i==0 and q%i==0:
#        gcd=i
#        break
#print(f"{a}和{b}的最大公约数为{gcd}")

Method 5: Stein Algorithm

The Stein algorithm is an algorithm for         calculating the greatest common divisor of two numbers. It is an improved algorithm for the defect that the Euclidean algorithm needs to be tested and increases the operation time when it operates on large integers.

Defects of Euclidean algorithm:

        Euclidean algorithm is a traditional algorithm for calculating the greatest common divisor of two numbers, which is very good both in theory and in terms of practical efficiency. But there is a fatal flaw. This flaw is generally not felt when the prime number is relatively small, and it will only appear when the prime number is large.

        Integers in general practical applications rarely exceed 64 bits (of course, 128 bits are allowed). For such integers, it is very simple to calculate the modulus between two numbers. For a platform with a word length of 32 bits, it only takes one instruction cycle to calculate the modulus of two integers not exceeding 32 bits, and it only takes a few cycles to calculate the modulus of integers below 64 bits. But for larger prime numbers, such a calculation process has to be designed by the user. In order to calculate the modulus of two integers exceeding 64 bits, the user may have to use a trial and error method similar to the manual calculation process of multi-digit division. This The process is not only complicated, but also consumes a lot of CPU time. For modern cryptographic algorithms , it is common to need to calculate prime numbers with more than 128 bits, and it is urgent to design such a program to abandon division and modulus.

Look at the following two conclusions:

        gcd(a,a)=a, that is, the common divisor of a number and itself is still itself.
        gcd(ka,kb)=k gcd(a,b), that is, the greatest common divisor operation and multiplication operation can be exchanged. In particular, when k=2, it means that the greatest common divisor of two even numbers must be divisible by 2.

        When k and b are prime numbers to each other, gcd(ka,b)=gcd(a,b), that is, the factors contained in only one of the two numbers are reduced without affecting the greatest common divisor. In particular, when k=2, it means that when calculating the greatest common divisor of an even number and an odd number, the even number can be divided by 2 first.

        :param a: the first number

        :param b: second number

        :return: greatest common divisor

def gcd_Stein(a, b):
    #  保证b比a小
    if a < b:
        a, b = b, a
    if (0 == b):
        return a
    #  a、b都是偶数,除2右移一位即可
    if a % 2 == 0 and b % 2 == 0:
        return 2 * gcd_Stein(a / 2, b / 2)
    #  a是偶数
    if a % 2 == 0:
        return gcd_Stein(a / 2, b)
    #  b是偶数
    if b % 2 == 0:
        return gcd_Stein(a, b / 2)
    #  都是奇数
    return gcd_Stein((a + b) / 2, (a - b) / 2)

a=int(input("please input the first number:"))
b=int(input("please input the second number:"))
gcd=int(gcd_Stein(a,b))
print(f"{a}和{b}的最大公约数为{gcd}")

The above are the five commonly used methods summarized by the editor, I hope it will be helpful to you! Remember to like it!

Guess you like

Origin blog.csdn.net/m0_69265664/article/details/125708828