NumPy LCM Lowest Common Multiple

M.Ramya

  How to Find the Lowest Common Multiple (LCM) in Python with NumPy

The Lowest Common Multiple (LCM) is the smallest positive integer that is a multiple of two or more numbers. It’s a handy calculation in mathematics, especially for solving problems involving fractions, ratios, and common denominators.

In this post, you’ll learn how to calculate the LCM of two numbers and even an entire array using Python and NumPy.

Program:

 Finding the LCM of Two Numbers

Python’s NumPy library makes finding the LCM easy with the np.lcm() function.

import numpy as np

num1 = 4

num2 = 6

x = np.lcm(num1, num2)

print(x)

Output:

12

Here, 12 is the smallest number that both 4 and 6 divide into evenly (4 × 3 = 12, 6 × 2 = 12).

 Finding the LCM of an Array of Numbers

To compute the LCM of multiple numbers, you can use NumPy’s reduce() method along with np.lcm.

This method applies the LCM function across all elements in the array.

Program:

import numpy as np

arr = np.array([3, 6, 9])

x = np.lcm.reduce(arr)

print(x)

Output:

18

Here, 18 is the LCM of 3, 6, and 9.

LCM of Numbers from 1 to 10

Need to find the LCM of a range of numbers?

Here’s how to find the LCM of numbers from 1 to 10:

Program:

import numpy as np

arr = np.arange(1, 11)

x = np.lcm.reduce(arr)

print(x)

Output:

2520

2520 is the smallest number that is evenly divisible by all numbers from 1 to 10.


Tags
Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send