Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

math.lcm() gives error "Module 'math' has no 'lcm' member"

I was making a simple calculator:

import math

number1 = input("Enter a number: ")
number2 = input("Enter a number: ")

result = math.lcm(int(number1), int(number2))

print(result)

when I got the error in the title. This works in the shell and even code as simple as

import math
math.lcm(10, 20)

gives me the error.

like image 855
pepo_boyii Avatar asked Sep 06 '25 02:09

pepo_boyii


1 Answers

Well, let's take a look at the documentation for math.lcm to see why it sometimes exists and sometimes doesn't exist!

  • The Doc

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:

  • StackOverflow: How do I check what version of Python is running my script?
  • Using the python 3.9 interpreter in Visual Studio Code [thanks to user:Jill Cheng for this link]
like image 127
Stef Avatar answered Sep 09 '25 19:09

Stef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!