Modular Exponentiation

Modular exponentiation can be said to be an extension of Binary exponentiation. It is very often used in problem solving to get the exponent within a range that does not cause integer overflow. It is utilised to calculate the exponent modulo to some other prime i.e., (ab) % p. Modular exponentiation uses the concept of both binary exponentiation and modular arithmetic.

This algorithm uses the concept of binary exponentiation to calculate the power in less time and the formula of modular multiplication as shown in the above section for getting the required value of the exponent.

Below is the implementation of Modular exponentiation:

C++
// C++ program to compute modular power
#include <bits/stdc++.h>
using namespace std;

// Iterative Function to calculate (x^y)%p in O(log y)
int power(long long x, unsigned int y, int p)
{
    int res = 1;

    // Update x if it is more than or equal to p
    x = x % p;

    // In case x is divisible by p
    if (x == 0)
        return 0;

    while (y > 0) {
        
        // If y is odd, multiply x with result
        if (y & 1)
            res = (res * x) % p;

        // y = y/2
        y = y >> 1;
        x = (x * x) % p;
    }
    return res;
}

// Driver code
int main()
{
    int x = 2, y = 5, p = 13;

    // Function  call
    cout << "Power is " << power(x, y, p);
    return 0;
}
Java
// Java program to compute modular power
import java.io.*;

class GFG {

    // Iterative Function to calculate (x^y) in O(log y)
    static int power(int x, int y, int p)
    {
        int res = 1;

        // Update x if it is more than or equal to p
        x = x % p;

        // In case x is divisible by p
        if (x == 0)
            return 0;

        while (y > 0) {
            
            // If y is odd, multiply x with result
            if ((y & 1) != 0)
                res = (res * x) % p;

            // y = y/2
            y = y >> 1;
            x = (x * x) % p;
        }
        return res;
    }

    // Driver Code
    public static void main(String[] args)
    {
        int x = 2, y = 5, p = 13;

        // Function call
        System.out.print("Power is " + power(x, y, p));
    }
}
Python3
# Python3 program to compute modular power


# Iterative Function to calculate (x^y)%p in O(log y)
def power(x, y, p):

    # Initialize result
    res = 1

    # Update x if it is more than or equal to p
    x = x % p

    # In case x is divisible by p;
    if (x == 0):
        return 0

    while (y > 0):
        # If y is odd, multiply x with result
        if ((y & 1) == 1):
            res = (res * x) % p

        # y = y/2
        y = y >> 1
        x = (x * x) % p

    return res


# Driver Code
if __name__ == '__main__':
    x = 2
    y = 5
    p = 13

    # Function call
    print("Power is", power(x, y, p))
C#
// C# program to compute modular power
using System;

public class GFG {

    // Iterative Function to calculate (x^y) in O(log y)
    static int power(int x, int y, int p)
    {
        int res = 1;

        // Update x if it is more than or equal to p
        x = x % p;

        // In case x is divisible by p
        if (x == 0)
            return 0;

        while (y > 0) {
          
            // If y is odd, multiply x with result
            if ((y & 1) != 0)
                res = (res * x) % p;

            // y = y/2
            y = y >> 1;
            x = (x * x) % p;
        }
        return res;
    }

    // Driver Code
    static public void Main()
    {
        int x = 2, y = 5, p = 13;

        // Function call
        Console.Write("Power is " + power(x, y, p));
    }
}
Javascript
// Javascript program to compute modular power

// Iterative Function to calculate (x^y)%p in O(log y)
function power(x, y, p)
{
    let res = 1;

    // Update x if it is more than or equal to p
    x = x % p;

    // In case x is divisible by p
    if (x == 0)
        return 0;

    while (y > 0)
    {
        // If y is odd, multiply x with result
        if (y & 1)
            res = (res * x) % p;

        // y = y/2
        y = y >> 1;
        x = (x * x) % p;
    }
    return res;
}

// Driver Code
let x = 2;
let y = 5;
let p = 13;

// Function call
console.log("Power is " + power(x, y, p));
PHP
<?php
// PHP program to compute modular power

// Iterative Function to calculate (x^y)%p in O(log y)
function power($x, $y, $p)
{
    $res = 1;

    // Update x if it is more than or equal to p
    $x = $x % $p;

    // In case x is divisible by p
    if ($x == 0)
        return 0;

    while ($y > 0)
    {
        // If y is odd, multiply x with result
        if ($y & 1)
            $res = ($res * $x) % $p;

        // y = $y/2
        $y = $y >> 1;
        $x = ($x * $x) % $p;
    }
    return $res;
}

// Driver Code
$x = 2;
$y = 5;
$p = 13;

// Function call
echo "Power is ", power($x, $y, $p);
?>

Output
Power is 6


Time Complexity: O(log(y))
Auxiliary Space: O(1)

Mathematical and Geometric Algorithms – Data Structure and Algorithm Tutorials

Mathematical and geometric algorithms stand as powerful tools for solving complex problems. These algorithms use mathematical and geometric principles to efficiently and elegantly manipulate and analyze data. In this tutorial, we will discuss in detail What are Mathematical and Geometrical Algorithms, When to use them, and how to make use of these algorithms in DSA.

Table of Content

  • What are Mathematical Algorithms?
  • Use cases of Mathematical Algorithms
  • Euclid Algorithm
  • Modular Arithmetic
  • Binary Exponentiation
  • Modular Exponentiation
  • Sieve of Eratosthenes
  • Other Useful Mathematical Concepts for Competitive Programming (CP)
  • What are Geometric Algorithms?
  • Use cases of Geometric Algorithms
  • Pattern Printing
  • Convex Hull

Similar Reads

What are Mathematical Algorithms?

Mathematical algorithm can be defined as an algorithm or procedure which is utilized to solve a mathematical problem, or mathematical problem which can be solved using DSA....

Use cases of Mathematical Algorithms:

It is a very useful topic for solving problems of computer science and also has vast applications in competitive programming. Some of them are mentioned below:...

Euclid Algorithm:

This is an algorithm to find the GCD of two numbers efficiently. A simple way to find the GCD of two numbers is to factorize both numbers and multiply the common factors. This algorithm is based on the following facts:...

Modular Arithmetic:

Modular arithmetic is another important topic of mathematics that is used in problem solving, especially in competitive programming. This concept is used often when we deal with very large integers and we are satisfied with the modulo answer (i.e., number % N). The concept of modulo is used to avoid the integer overflow error. On many platforms, the values of N are often kept as 109 + 7 or 998244353. Both of these are large primes and we can fit a large range of numbers....

Binary Exponentiation:

This is a useful way to calculate the powers of any number i.e., ab. To do this, we generally multiply ‘a‘ with itself ‘b‘ times. Let us have a look at the following exponent expression:...

Modular Exponentiation:

Modular exponentiation can be said to be an extension of Binary exponentiation. It is very often used in problem solving to get the exponent within a range that does not cause integer overflow. It is utilised to calculate the exponent modulo to some other prime i.e., (ab) % p. Modular exponentiation uses the concept of both binary exponentiation and modular arithmetic....

Sieve of Eratosthenes:

This is one of the most used mathematical algorithms. The Sieve of Eratosthenes is used to find all the prime numbers upto any value N. Though there is another way to find the primes by iterating all numbers till N and checking each of them, that is not efficient. It takes time of O(N*sqrt(N)) time, whereas, using the Sieve of Eratosthenes, we can find the primes in O(N*log(logN)) time....

Other Useful Mathematical Concepts for Competitive Programming (CP):

The above mentioned algorithms are some of the most important algorithms and concepts. Apart from these, there are also some general mathematical concepts that come in handy while we are practicing programming or participating in competitive programming. Those are mentioned below:...

What are Geometric Algorithms?

In different areas of computer science such as robotics, data analysis, computer graphics, virtual reality and etc we need to deal with the geometric aspect or spatial data. The algorithms devised to deal with these types of data are known as geometric algorithms....

Use cases of Geometric Algorithms:

Data mining: It is very much useful in data mining. Finding the relations between two points are based on the usage of geometric algorithms.Simulation: For simulations of real-life objects we need to understand their geometry and reflect it properly. This is the aspect where geometric algorithms come in handy.Virtual Reality: The usage of these algorithms can be experienced in virtual reality. How to transfer the points and their relative spacing requires the usage of these algorithms....

Pattern Printing:

To understand the basic working of loops, a newcomer goes through pattern printing. Printing several patterns require knowledge of the geometric shape of those and how an algorithm can be devised to print those patterns on the screen of computer. Some common patterns are provided here for your practice....

Convex Hull:

The Convex Hull algorithm is a fundamental algorithm in computational geometry used to find the smallest convex polygon that encloses a set of points. It is commonly employed in various areas such as pattern recognition, image processing, and geographic information systems. The algorithm plays a key role in identifying the outer boundary of a set of points, making it a valuable tool in spatial analysis and computational geometry....

Contact Us