Skip to content
Related Articles

Related Articles

Find (a^b)%m where ‘b’ is very large

Improve Article
Save Article
  • Difficulty Level : Hard
  • Last Updated : 16 Aug, 2022
Improve Article
Save Article

Given three numbers a, b and m where 1<=a, m<=10^6. Given very large ‘b’ containing up to 10^6 digits and m is a prime number, the task is to find (a^b)%m.
Examples: 

Input: a = 2, b = 3, m = 17 
Output:
2 ^ 3 % 17 = 8
Input: a = 3, b = 100000000000000000000000000, m = 1000000007 
Output: 835987331

Iterative Approach: According to Fermat’s little theorem and Modular Exponentiation,

a^(p-1) mod p = 1, When p is prime.

From this, as of the problem, M is prime, express A^B mod M as follows: 

A^B mod M = ( A^(M-1) * A^(M-1) *.......* A^(M-1) * A^(x) ) mod M

Where x is B mod M-1 and A ^ (M-1) continues B/(M-1) times
Now, from Fermat’s Little Theorem,  

A ^ (M-1) mod M = 1.

Hence, 

A^B mod M = ( 1 * 1 * ....... * 1 * A^(x) ) mod M

Hence mod B with M-1 to reduce the number to a smaller one and then use power() method to compute (a^b)%m
Below is the implementation of the above approach:  

C++




// C++ program to find
// (a^b)%m for b very large.
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
 
// Function to find power
ll power(ll x, ll y, ll p)
{
    ll res = 1; // Initialize result
 
    // Update x if it is more than or
    // equal to p
    x = x % p;
 
    while (y > 0) {
       
        // If y is odd, multiply x
        // with the result
        if (y & 1)
            res = (res * x) % p;
 
        // y must be even now
        y = y >> 1; // y = y/2
        x = (x * x) % p;
    }
    return res;
}
// Driver Code
int main()
{
    ll a = 3;
 
    // String input as b is very large
    string b = "100000000000000000000000000";
 
    ll remainderB = 0;
    ll MOD = 1000000007;
 
    // Reduce the number B to a small number
    // using Fermat Little
    for (int i = 0; i < b.length(); i++)
        remainderB = (remainderB * 10 +
                       b[i] - '0') % (MOD - 1);
 
    cout << power(a, remainderB, MOD) << endl;
    return 0;
}

Java




// Java program to find
// (a^b)%m for b very large.
import java.io.*;
 
class GFG
{
     
// Function to find power
static long power(long x,
                  long y, long p)
{
    long res = 1; // Initialize result
 
    // Update x if it is more
    // than or equal to p
    x = x % p;
 
    while (y > 0)
    {
        // If y is odd, multiply
        // x with the result
        if ((y & 1) > 0)
            res = (res * x) % p;
 
        // y must be even now
        y = y >> 1; // y = y/2
        x = (x * x) % p;
    }
    return res;
}
 
// Driver Code
public static void main (String[] args)
{
long a = 3;
 
// String input as
// b is very large
String b = "100000000000000000000000000";
 
long remainderB = 0;
long MOD = 1000000007;
 
// Reduce the number B to a small
// number using Fermat Little
for (int i = 0; i < b.length(); i++)
    remainderB = (remainderB * 10 +
                  b.charAt(i) - '0') %
                 (MOD - 1);
 
System.out.println(power(a, remainderB, MOD));
}
}
 
// This code is contributed by anuj_67.

Python3




# Python3 program to find
# (a^b)%m for b very large.
 
# Function to find power
def power(x, y, p):
    res = 1 # Initialize result
 
    # Update x if it is
    # more than or equal to p
    x = x % p
 
    while (y > 0):
         
        # If y is odd, multiply
        # x with the result
        if (y & 1):
            res = (res * x) % p
 
        # y must be even now
        y = y >> 1 # y = y/2
        x = (x * x) % p
         
    return res
 
# Driver Code
a = 3
 
# String input as b
# is very large
b = "100000000000000000000000000"
 
remainderB = 0
MOD = 1000000007
 
# Reduce the number B
# to a small number
# using Fermat Little
for i in range(len(b)):
    remainderB = ((remainderB * 10 +
                   ord(b[i]) - 48) %
                   (MOD - 1))
 
print(power(a, remainderB, MOD))
 
# This code is contributed by mits

C#




// C# program to find
// (a^b)%m for b very large.
using System;
 
class GFG
{
     
// Function to find power
static long power(long x,
                  long y, long p)
{
    // Initialize result
    long res = 1;
 
    // Update x if it is more
    // than or equal to p
    x = x % p;
 
    while (y > 0)
    {
        // If y is odd, multiply
        // x with the result
        if ((y & 1) > 0)
            res = (res * x) % p;
 
        // y must be even now
        y = y >> 1; // y = y/2
        x = (x * x) % p;
    }
    return res;
}
 
// Driver Code
public static void Main ()
{
    long a = 3;
     
    // String input as
    // b is very large
    string b = "100000000000000000000000000";
     
    long remainderB = 0;
    long MOD = 1000000007;
     
    // Reduce the number B to
    // a small number using
    // Fermat Little
    for (int i = 0; i < b.Length; i++)
        remainderB = (remainderB * 10 +
                          b[i] - '0') %
                             (MOD - 1);
     
    Console.WriteLine(power(a, remainderB, MOD));
}
}
 
// This code is contributed by anuj_67.

PHP




<?php
// PHP program to find
// (a^b)%m for b very large.
 
// Function to find power
function power($x, $y, $p)
{
    $res = 1; // Initialize result
 
    // Update x if it is
    // more than or equal to p
    $x = $x % $p;
 
    while ($y > 0)
    {
        // If y is odd, multiply
        // x with the result
        if ($y & 1)
            $res = ($res * $x) % $p;
 
        // y must be even now
        $y = $y >> 1; // y = y/2
        $x = ($x * $x) % $p;
    }
    return $res;
}
 
// Driver Code
$a = 3;
 
// String input as b
// is very large
$b = "100000000000000000000000000";
 
$remainderB = 0;
$MOD = 1000000007;
 
// Reduce the number B
// to a small number
// using Fermat Little
for ($i = 0; $i < strlen($b); $i++)
    $remainderB = ($remainderB * 10 +
                   $b[$i] - '0') %
                  ($MOD - 1);
 
echo power($a, $remainderB, $MOD);
 
// This code is contributed by mits
?>

Javascript




// JavaScript program to find
// (a^b)%m for b very large.
 
// Function to find power
function power(x, y, p)
{
    let res = 1n; // Initialize result
 
    // Update x if it is more than or
    // equal to p
    x = x % p;
 
    while (y > 0n) {
       
        // If y is odd, multiply x
        // with the result
        if (y & 1n)
            res = (res * x) % p;
 
        // y must be even now
        y = y >> 1n; // y = y/2
        x = (x * x) % p;
    }
    return res;
}
// Driver Code
let a = 3n;
 
// String input as b is very large
let b = "100000000000000000000000000";
 
let remainderB = 0n;
let MOD = 1000000007n;
 
// Reduce the number B to a small number
// using Fermat Little
for (var i = 0; i < b.length; i++)
        remainderB = (remainderB * 10n +
                       BigInt(b.charAt(i))) % (MOD - 1n);
 
console.log(power(a, remainderB, MOD));
 
// This code is contributed by phasing17

Output

835987331

Time Complexity: O(len(b)+log b)

Auxiliary Space: O(1)

Recursive Approach: It is same to the above implementation except the fact that we have to pass each subproblem result to the backtracking recursion stack.

C++14




#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
 
// Reduce the number B to a small number
    // using Fermat Little
ll MOD(string num,int mod)
{
    ll res=0;
     
    for(int i=0;i<num.length();i++)
    res=(res*10+num[i]-'0')%(mod-1);
     
    return res;
}
 
ll ModExponent(ll a,ll b,ll m)
{
    ll result;
    if(a==0)
    return 0;
    else if(b==0)
    return 1;
    else if(b&1)
    {
        result=a%m;
        result=result*ModExponent(a,b-1,m);
    }
    else{
        result=ModExponent(a,b/2,m);
        result=((result%m)*(result%m))%m;
    }
    return (result%m+m)%m;
}
 
int main()
{
    ll a = 3;
    // String input as b is very large
    string b = "100000000000000000000000000";
    ll m = 1000000007;
    ll remainderB = MOD(b,m);
  
    cout << ModExponent(a, remainderB, m) << endl;
     
    return 0;
}

Java




// Java program to implement the approach
import java.util.*;
class GFG
{
 
  // Reduce the number B to a small number
  // using Fermat Little
  static long MOD(String num, long mod)
  {
    long res = 0;
 
    for (int i = 0; i < num.length(); i++)
      res = (res * 10 + num.charAt(i) - '0')
      % (mod - 1);
 
    return res;
  }
 
  static long ModExponent(long a, long b, long m)
  {
    long result;
    if (a == 0)
      return 0;
    else if (b == 0)
      return 1;
    else if ((b & 1) != 0) {
      result = a % m;
      result = result * ModExponent(a, b - 1, m);
    }
    else {
      result = ModExponent(a, b / 2, m);
      result = ((result % m) * (result % m)) % m;
    }
    return (result % m + m) % m;
  }
 
  public static void main(String[] args)
  {
    long a = 3;
 
    // String input as b is very large
    String b = "100000000000000000000000000";
    long m = 1000000007;
    long remainderB = MOD(b, m);
 
    System.out.println(ModExponent(a, remainderB, m));
  }
}
 
// This code is contributed by phasing17

Python3




# Python3 code to implement the approach
 
# Reduce the number B to a small number
# using Fermat Little
def MOD(num, mod):
    res = 0;
 
    for i in range(len(num)):
        res = (res * 10 + int(num[i])) % (mod - 1);
    return res;
 
def ModExponent(a, b, m):
 
    if (a == 0):
        return 0;
    elif (b == 0):
        return 1;
    elif (b & 1):
        result = a % m;
        result = result * ModExponent(a, b - 1, m);
     
    else:
        result = ModExponent(a, b // 2, m);
        result = ((result % m) * (result % m)) % m;
     
    return (result % m + m) % m
 
# Driver Code
a = 3;
 
# String input as b is very large
b = "100000000000000000000000000";
m = 1000000007;
remainderB = MOD(b, m);
 
print(ModExponent(a, remainderB, m));
 
# This code is contributed by phasing17

C#




// C# program to implement the approach
using System;
 
class GFG
{
 
  // Reduce the number B to a small number
  // using Fermat Little
  static long MOD(string num, long mod)
  {
    long res = 0;
 
    for (int i = 0; i < num.Length; i++)
      res = (res * 10 + num[i] - '0') % (mod - 1);
 
    return res;
  }
 
  static long ModExponent(long a, long b, long m)
  {
    long result;
    if (a == 0)
      return 0;
    else if (b == 0)
      return 1;
    else if ((b & 1) != 0) {
      result = a % m;
      result = result * ModExponent(a, b - 1, m);
    }
    else {
      result = ModExponent(a, b / 2, m);
      result = ((result % m) * (result % m)) % m;
    }
    return (result % m + m) % m;
  }
 
  public static void Main(string[] args)
  {
    long a = 3;
 
    // String input as b is very large
    string b = "100000000000000000000000000";
    long m = 1000000007;
    long remainderB = MOD(b, m);
 
    Console.WriteLine(ModExponent(a, remainderB, m));
  }
}
 
// This code is contributed by phasing17

Javascript




// JavaScript code to implement the approach
 
// Reduce the number B to a small number
// using Fermat Little
function MOD(num, mod)
{
    let res = 0n;
 
    for (let i = 0; i < num.length; i++)
        res = (res * 10n + BigInt(num.charAt(i)))
              % (mod - 1n);
 
    return res;
}
 
function ModExponent(a, b, m)
{
    let result;
    if (a == 0n)
        return 0n;
    else if (b == 0n)
        return 1n;
    else if (b & 1n) {
        result = a % m;
        result = result * ModExponent(a, b - 1n, m);
    }
    else {
        result = ModExponent(a, ((b - (b % 2n)) / 2n), m);
        result = ((result % m) * (result % m)) % m;
    }
    return (result % m + m) % m;
}
 
let a = 3n;
 
// String input as b is very large
let b = "100000000000000000000000000";
let m = 1000000007n;
let remainderB = MOD(b, m);
 
console.log(ModExponent(a, remainderB, m));
 
// This code is contributed by phasing17

Output

835987331

Time Complexity: O(len(b)+log b)

Auxiliary Space: O(log b)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!