kzoacn's blog

By kzoacn, history, 7 years ago, In English

I write two code to compute gcd in python3, but math.gcd is much faster than gcd.

Here is my code.

def gcd(a, b): 
	while a:
		a, b = b % a, a
	return b
x, y = map(int, input().split())
print(gcd(x, y))

And another code.

import math
x, y = map(int, input().split())
print(math.gcd(x, y))

What's the implemention of math.gcd? Thanks in advance.

  • Vote: I like it
  • +25
  • Vote: I do not like it

»
7 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by kzoacn (previous revision, new revision, compare).

»
7 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by kzoacn (previous revision, new revision, compare).

»
7 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by kzoacn (previous revision, new revision, compare).

»
7 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by kzoacn (previous revision, new revision, compare).

»
7 years ago, # |
  Vote: I like it +2 Vote: I do not like it

I think, maybe math.gcd is speeded by cplusplus to improve its efficiency.

»
7 years ago, # |
Rev. 2   Vote: I like it +24 Vote: I do not like it

Because it is actually a C function. Search for _PyLong_GCD in this.