Python Greatest common divisor

Source: Internet
Author: User
Tags gcd greatest common divisor

Greatest common divisor for solving two integers (not negative numbers) (requires two numbers not being 0)

When both numbers are 0 o'clock, greatest common divisor is 0.

Way one: the poor lifting method
1 defGCU (M, n):2     if  notm:3         returnN4     elif  notN:5         returnm6     elifM isN:7         returnm8 9     ifM >N:TenGCD =N One     Else: AGCD =m -  -      whileM%gcdorn%GCD: theGCD-= 1 -  -     returngcd
View Code

Method Two: Phase subtraction

1 defGCU (M, n):2     if  notm:3         returnN4     elif  notN:5         returnm6     elifM isN:7         returnm8 9      whilem!=N:Ten         ifM>N: OneM-=N A         Else: -N-=m -  the     returnM
View Code

Way three: Euclid's Euclidean method

1 defGCU (M, n):2     if  notm:3         returnN4     elif  notN:5         returnm6     elifM isN:7         returnm8 9      whilem%N:Tenm, n = N, m%N One  A     returnN
View Code

Mode four: Euclid's method of dividing the number of miles to achieve recursion

1 defGCU (m,n):2     if  notN:3         returnm4     Else:5         returnGCU (N, m%N)6 7 if __name__=='__main__':8a = Int (input ('Please input the first integers:'))9b = Int (input ('Please input the second integers:'))Tenresult =GCU (A, b) One     Print('GCU =', result)
View Code

Python Greatest common divisor

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.