Chapter 05 of 08

Mathematical Algorithms (GCD, LCM, Prime Numbers, Sieve of Eratosthenes & Fast Power)

Mathematical Algorithms (GCD, LCM, Prime Numbers, Sieve of Eratosthenes & Fast Power)

So far, we've learned how algorithms work, how recursion solves problems, and how bit manipulation helps us perform extremely fast operations. Now it's time to learn another important topic in Data Structures and Algorithms—Mathematical Algorithms.

You might think mathematics is only useful for solving equations in school, but in programming, mathematics helps us solve problems faster, smarter, and more efficiently.

Many coding interview questions and competitive programming problems involve concepts like finding the Greatest Common Divisor (GCD), calculating the Least Common Multiple (LCM), checking whether a number is Prime, generating all prime numbers using the Sieve of Eratosthenes, or calculating huge powers using Fast Power.

The infographic beautifully presents these five concepts as different stops in a "Number Kingdom." Let's explore each one step by step.


Why Do We Need Mathematical Algorithms?

The compiler in the infographic says:

We use mathematics to solve problems smarter and faster!

Imagine you need to solve the same mathematical problem millions of times.

A simple solution may work,

but an optimized mathematical algorithm can reduce the execution time dramatically.

For example,

finding the GCD using repeated subtraction may take hundreds of operations,

while Euclid's Algorithm solves the same problem in just a few steps.

This is why mathematical algorithms are widely used in:

  • Competitive Programming

  • Cryptography

  • Number Theory

  • Modular Arithmetic

  • Efficient Computation


1. Greatest Common Divisor (GCD)

The first stop in the infographic is GCD.

It is defined as:

Find the greatest number that divides both numbers.

Suppose we have:

24 and 36

Let's list their factors.

Factors of 24:

1, 2, 3, 4, 6, 8, 12, 24

Factors of 36:

1, 2, 3, 4, 6, 9, 12, 18, 36

Common factors are:

1, 2, 3, 4, 6, 12

The greatest among them is:

12

Therefore,

GCD(24, 36) = 12

Exactly as shown in the infographic.


Euclidean Algorithm

Instead of checking every factor, programmers use the Euclidean Algorithm, which is much faster.

The infographic shows this algorithm.

Let's write it in Java.

static int gcd(int a, int b) {
    if (b == 0)
        return a;

    return gcd(b, a % b);
}

Let's understand what happens with the example:

GCD(24,36)

First,

gcd(24,36)

↓

gcd(36,24)

because

36 % 24 = 12

Now,

gcd(24,12)

Again,

24 % 12 = 0

Now,

gcd(12,0)

Since b == 0,

the answer becomes:

12

Exactly what we expected.

The infographic also mentions that the time complexity is O(log n), making Euclid's Algorithm one of the fastest ways to compute the GCD.


2. Least Common Multiple (LCM)

The next stop is LCM.

LCM stands for:

Least Common Multiple

It means:

The smallest positive number that is divisible by both numbers.

The infographic uses:

24

36

The answer shown is:

72

Let's verify.

72 ÷ 24 = 3

72 ÷ 36 = 2

Since 72 is divisible by both,

it is the LCM.


Relationship Between GCD and LCM

One beautiful mathematical relationship is shown in the infographic.

LCM(a,b) = (a × b) / GCD(a,b)

Using the same example,

24 × 36 = 864

Now divide by the GCD.

864 ÷ 12 = 72

Perfect.

This formula avoids calculating multiples manually.


Java Code for LCM

The infographic provides the idea.

Here's the Java version.

static int lcm(int a, int b) {
    return (a / gcd(a, b)) * b;
}

Notice that we divide before multiplying to reduce the risk of integer overflow.

The time complexity is still O(log n) because it mainly depends on the GCD calculation.


3. Prime Numbers

The third section introduces Prime Numbers.

A Prime Number is defined as:

A number having exactly two factors.

Those two factors are:

  • 1

  • The number itself

The infographic highlights examples like:

2

3

5

7

11

13

These are all prime numbers.


Prime vs Composite

The infographic compares:

7

and

9

Let's understand why.

For 7,

Factors are:

1

7

Only two factors.

Therefore,

7 is Prime.


Now look at 9.

Factors:

1

3

9

Three factors.

So,

9 is a Composite Number.

This is exactly why the infographic marks 7 as Prime and 9 as Composite.


Java Code to Check Prime

The infographic provides a basic algorithm.

Here's the Java version.

static boolean isPrime(int n) {

    if (n < 2)
        return false;

    for (int i = 2; i * i <= n; i++) {

        if (n % i == 0)
            return false;
    }

    return true;
}

Notice something important.

We don't check divisibility up to n.

Instead,

we stop at:

i * i <= n

or √n.

Why?

Because if a number has a factor larger than √n,

the corresponding smaller factor would already have been found earlier.

This optimization reduces the time complexity to O(√n), exactly as mentioned in the infographic.


4. Sieve of Eratosthenes

Suppose someone asks you:

Find all prime numbers from 1 to 1,000,000.

Calling isPrime() one million times would be slow.

Instead,

we use one of the most famous algorithms in mathematics—

The Sieve of Eratosthenes.

The infographic explains it beautifully.

Start with every number marked as Prime.

Then,

begin from:

2

Mark all multiples of 2.

Then move to:

3

Mark every multiple of 3.

Then:

5

Then:

7

Eventually,

only prime numbers remain unmarked.

The infographic clearly shows composite numbers being crossed out while prime numbers remain highlighted.


Java Code for Sieve

Here's the Java version of the algorithm.

static boolean[] sieve(int n) {

    boolean[] prime = new boolean[n + 1];

    Arrays.fill(prime, true);

    prime[0] = false;
    prime[1] = false;

    for (int i = 2; i * i <= n; i++) {

        if (prime[i]) {

            for (int j = i * i; j <= n; j += i) {
                prime[j] = false;
            }
        }
    }

    return prime;
}

The infographic mentions that this algorithm runs in:

O(n log log n)

This is much faster than checking every number individually when generating many prime numbers.


5. Fast Power (Binary Exponentiation)

The final topic in the infographic is Fast Power.

Imagine calculating:

2¹⁶

A beginner might multiply:

2 × 2 × 2 × 2 × ...

sixteen times.

That works,

but it's not efficient.

Instead,

Fast Power uses the idea of repeated squaring.

The infographic illustrates this by showing powers such as:

2¹

2²

2⁴

2⁸

2¹⁶

Rather than multiplying by 2 repeatedly, we square the result at each step, reducing the number of operations dramatically.

This is why the infographic says:

Jump & Multiply Smartly!


Java Code for Fast Power

The infographic shows the algorithm in C-like syntax. Here's the Java version.

static long power(long a, long b) {

    long ans = 1;

    while (b > 0) {

        if ((b & 1) == 1)
            ans *= a;

        a *= a;
        b >>= 1;
    }

    return ans;
}

Let's understand it using:

2⁵

Initially,

ans = 1

a = 2

b = 5

Since 5 is odd,

multiply:

ans = 2

Square a:

4

Halve b:

2

Again,

square a:

16

Halve b:

1

Since 1 is odd,

multiply:

2 × 16 = 32

Final answer:

32

Exactly equal to:

2⁵

Instead of performing five multiplications, Binary Exponentiation finishes the work in O(log n) time.


Common Bit Tricks

The infographic also includes a quick reminder of some useful bit manipulation tricks because Fast Power relies on bitwise operations.

Check Odd or Even

(num & 1)

If the last bit is 1,

the number is odd.

Otherwise,

it's even.


Swap Without Temporary Variable

a ^= b;
b ^= a;
a ^= b;

A classic XOR trick.


Count Set Bits

Count the number of 1s in the binary representation.

In Java, you can simply use:

int count = Integer.bitCount(num);

Power of Two

(num & (num - 1)) == 0

If true,

the number is a power of two.


Applications of Mathematical Algorithms

The infographic highlights several important applications.

Competitive Programming

Many coding contest problems require optimized mathematical algorithms.


Cryptography

Modern encryption algorithms rely heavily on modular arithmetic, prime numbers, and fast exponentiation.


Number Theory

Many mathematical problems involve GCD, LCM, and prime numbers.


Modular Arithmetic

Fast Power is commonly used for modular exponentiation in programming contests and cryptographic systems.


Efficient Computation

Optimized mathematical algorithms reduce execution time significantly when handling very large inputs.


Why Learn Mathematical Algorithms?

The infographic concludes with several reasons.

Mathematical algorithms are:

  • Extremely fast.

  • Memory efficient.

  • Useful for low-level optimization.

  • Essential in many advanced algorithms.

Instead of solving problems using brute force,

these techniques allow us to solve them using elegant mathematical ideas.


Time Complexities

Let's summarize the time complexity of the algorithms shown in the infographic:

Algorithm

Time Complexity

Euclidean GCD

O(log n)

LCM (using GCD)

O(log n)

Prime Check

O(√n)

Sieve of Eratosthenes

O(n log log n)

Fast Power

O(log n)

Most Bit Operations

O(1)


A Few Important Things to Know

There are a few useful concepts that aren't explicitly shown in the infographic but are worth understanding:

  • GCD and LCM are closely related. For positive integers, GCD(a, b) × LCM(a, b) = a × b.

  • 2 is the only even prime number. Every other even number has at least three factors, making it composite.

  • The Sieve of Eratosthenes is ideal when you need many prime numbers. If you only need to check one number, the isPrime() method is usually more appropriate.

  • Fast Power is often combined with modulo operations (known as Modular Exponentiation) in competitive programming to handle extremely large powers without integer overflow.

  • Bitwise operations make Fast Power efficient. Checking whether an exponent is odd using (b & 1) and dividing it by two using b >>= 1 are key optimizations.


Conclusion

Mathematical algorithms are some of the most powerful tools in programming because they replace slow, repetitive calculations with efficient mathematical techniques. Whether you're finding the GCD of two numbers, computing the LCM, checking for prime numbers, generating all primes using the Sieve of Eratosthenes, or calculating huge powers using Binary Exponentiation, these algorithms help solve problems faster while using minimal resources. Mastering these concepts will not only improve your coding skills but also prepare you for coding interviews, competitive programming, and advanced algorithm design.


Quick Revision

Concept

Remember

GCD

Greatest number that divides both numbers. Uses Euclid's Algorithm.

LCM

Smallest number divisible by both numbers. LCM = (a × b) / GCD.

Prime Number

Has exactly two factors: 1 and itself.

Composite Number

Has more than two factors.

Prime Check

Check divisibility only up to √nO(√n).

Sieve of Eratosthenes

Generates all prime numbers efficiently → O(n log log n).

Fast Power

Uses repeated squaring (Binary Exponentiation) → O(log n).

Bit Tricks

Odd/Even, Count Set Bits, Power of Two, XOR Swap.

Applications

Competitive Programming, Cryptography, Number Theory, Modular Arithmetic.

Key Idea

Use mathematics and optimized algorithms to solve problems faster instead of brute force.