Well, let's take a look at the documentation for math.lcm
to see why it sometimes exists and sometimes doesn't exist!
What's it says? New in version 3.9.
Looks like your code works when run with python 3.9, and doesn't work when run with python 3.8 or older.
Quick fix, python 3.5 to 3.8
On the other hand, math.gcd
exists since version 3.5. If you need an lcm
function in python 3.5, 3.6, 3.7 or 3.8, you can write it this way:
import math
def lcm(a,b):
return (a * b) // math.gcd(a,b)
Quick fix, python < 3.5
So lcm
is in math
since 3.9, and gcd
is in math
since 3.5. What if your python version is even older than that?
In older versions, gcd
wasn't in math
, but it was in fractions
. So this should work:
import fractions
def lcm(a,b):
return (a * b) // fractions.gcd(a,b)
Which python version am I using?
Please let me refer you to the kind user who asked that exact question: