How Python obtains greatest common divisor

Source: Internet
Author: User
Tags greatest common divisor
This time for you to bring Python how to get greatest common divisor, Python to find greatest common divisor attention to what, the following is the actual case, together to see.

Before summarizing the greatest common divisor solution in Gartner TAOCP, in fact, the algorithm modification in the after-class problem is to solve the greatest common divisor by the method of the Euclidean division.

My initial understanding of this topic was wrong, and naturally I did not make the standard answer. Now follow the answer to the answer to write the corresponding code implementation:

#-*-Coding:utf-8-*-#! Python2def maxcommpisor (m,n): While  m * n! = 0:    m = m% n    if m = = 0:      return n    else:      n = n% m      if n = = 0:        return mprint (Maxcommpisor (55,120))

Execution results of the program:

Swap the position of two digits with the following code:

#-*-Coding:utf-8-*-#! Python2def maxcommpisor (m,n): While  m * n! = 0:    m = m% n    if m = = 0:      return n    else:      n = n% m< c14/>if n = = 0:        return mprint (Maxcommpisor (120,55))

Execution results of the program:

It is mentioned in the topic that the efficiency can be reduced by the above code, and the loss of efficiency should be based on division and judgment. Here, compare the code of the previous algorithm:

def commdevisor (m,n):  r = m% n while r! =  0:    m = n    n = r    r = m% n  return Nprint (Commdevisor (120, 25))

Operation Result:

The new algorithm has a more division and comparison operation in the loop. In fact, the efficiency of comparison is good, but the operation of Division will lead to the reduction of efficiency.

Believe that you have read the case of this article you have mastered the method, more exciting please pay attention to the PHP Chinese network other related articles!

Recommended reading:

Python NumPy How to manipulate arrays and matrices

How to manipulate Python traversal numpy array

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.