Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Calculating Greatest Common Divisor and Least Common Multiple in Python

Tech May 17 3

Today we will explore how to compute the greatest common divisor (GCD) and least common multiple (LCM) of two integers using Python. This is a fundamental mathematical operation that can be implemented efficiently through various approaches.

Introduction

For many Python enthusiasts, mastering core syntax and concepts is just the beginning. To truly grasp the language, hands-on practice is essential. In this article, we'll demonstrate practical examples related to basic arithmetic operations in Python, including finding GCD and LCM.

Basic Airthmetic Example

The following script demonstrates how to calculate the sum of two numbers entered by the user:

# Prompting user for input
first_number = input('Enter first number: ')
second_number = input('Enter second number: ')

# Calculating the sum
total = float(first_number) + float(second_number)

# Displaying the result
print('Sum of {0} and {1} is {2}'.format(first_number, second_number, total))

When executed, the program produces output like:

Enter first number: 1.5
Enter second number: 2.5
Sum of 1.5 and 2.5 is 4.0

Generating Random Numbers

Here’s an example showing how to generate a random integer between 0 and 9:

import random
print(random.randint(0, 9))

Each execution returns a different value within the specified range, using the randint() function from the random module.

Finding Prime Numbers Within a Range

This code snippet identifies all prime numbers within a given interval:

lower_bound = int(input("Enter lower bound: "))
upper_bound = int(input("Enter upper bound: "))

for number in range(lower_bound, upper_bound + 1):
    if number > 1:
        for divisor in range(2, number):
            if number % divisor == 0:
                break
        else:
            print(number)

Executing this script results in a list of primes within the defined bounds.

Determining Days in a Month

Using the calendar module, one can determine the number of days in a particular month:

import calendar
days_info = calendar.monthrange(2016, 9)
print(days_info)

Output:

(3, 30)

This tuple indicates that September 2016 started on a Thursday (index 3), and had 30 days in total.

Clearing a List

To remove all element from a list, you can use the clear() method:

my_list = [6, 0, 4, 1]
print('Before clearing:', my_list)
my_list.clear()
print('After clearing:', my_list)

Result:

Before clearing: [6, 0, 4, 1]
After clearing: []

Practical Implementation of GCD and LCM

Here's a more direct implementation for calculating both GCD and LCM:

def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

def lcm(a, b):
    return abs(a * b) // gcd(a, b)

num1 = int(input("Enter first integer: "))
num2 = int(input("Enter second integer: "))

print(f"GCD of {num1} and {num2} is {gcd(num1, num2)}")
print(f"LCM of {num1} and {num2} is {lcm(num1, num2)}")

This approach uses Euclid’s algorithm for computing the GCD, which is efficient and widely used in programming.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.