The Wayback Machine - https://web.archive.org/web/20240627105640/https://www.geeksforgeeks.org/find-abm-large/
Open In App

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

Last Updated : 11 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given three numbers a, b and m where 1<=b,m<=10^6 and ‘a’ may be very large and contains upto 10^6 digits. The task is to find (a^b)%m.

Examples: 

Input  : a = 3, b = 2, m = 4
Output : 1
Explanation : (3^2)%4 = 9%4 = 1

Input : a = 987584345091051645734583954832576, b = 3, m = 11
Output: 10
Recommended Practice

This problem is basically based on modular arithmetic. We can write (a^b) % m as (a%m) * (a%m) * (a%m) * … (a%m), b times. Below is a algorithm to solve this problem : 

  • Since ‘a’ is very large so read ‘a’ as string.
  • Now we try to reduce ‘a’. We take modulo of ‘a’ by m once, i.e; ans = a % m , in this way now ans=a%m lies between integer range 1 to 10^6 i.e; 1 <= a%m <= 10^6.
  • Now multiply ans by b-1 times and simultaneously take mod of intermediate multiplication result with m because intermediate multiplication of ans may exceed range of integer and it will produce wrong answer.

C++




// C++ program to find (a^b) mod m for a large 'a'
#include<bits/stdc++.h>
using namespace std;
  
// utility function to calculate a%m
unsigned int aModM(string s, unsigned int mod)
{
    unsigned int number = 0;
    for (unsigned int i = 0; i < s.length(); i++)
    {
        // (s[i]-'0') gives the digit value and form
        // the number
        number = (number*10 + (s[i] - '0'));
        number %= mod;
    }
    return number;
}
  
// Returns find (a^b) % m
unsigned int ApowBmodM(string &a;, unsigned int b,
                                  unsigned int m)
{
    // Find a%m
    unsigned int ans = aModM(a, m);
    unsigned int mul = ans;
  
    // now multiply ans by b-1 times and take
    // mod with m
    for (unsigned int i=1; i<b; i++)
        ans = (ans*mul) % m;
  
    return ans;
}
  
// Driver program to run the case
int main()
{
    string a = "987584345091051645734583954832576";
    unsigned int b=3, m=11;
    cout << ApowBmodM(a, b, m);
    return 0;
}


Java




// Java program to find (a^b) mod m for a large 'a'
  
public class GFG {
      
    // utility function to calculate a%m
    static int aModM(String s, int mod)
    {
        int number = 0;
        for (int i = 0; i < s.length(); i++)
        {
              
            // (s[i]-'0') gives the digit
            // value and form the number
            number = (number * 10 );
            int x = Character.getNumericValue(s.charAt(i));
            number = number + x;
            number %= mod;
        }
          
        return number;
    }
  
    // Returns find (a^b) % m
    static int ApowBmodM(String a, int b, int m)
    {
          
        // Find a%m
        int ans = aModM(a, m);
        int mul = ans;
      
        // now multiply ans by b-1 times 
        // and take mod with m
        for (int i = 1; i < b; i++)
            ans = (ans * mul) % m;
      
        return ans;
    }
  
    // Driver code
    public static void main(String args[])
    {
        String a = "987584345091051645734583954832576";
        int b = 3, m = 11;
        System.out.println(ApowBmodM(a, b, m));
    }
}
  
// This code is contributed by Sam007


Python3




# Python program to find (a^b) mod m for a large 'a'
def aModM(s, mod):
    number = 0
  
    # convert string s[i] to integer which gives
    # the digit value and form the number
    for i in range(len(s)):
        number = (number*10 + int(s[i]))
        number = number % m
  
    return number
  
# Returns find (a^b) % m
def ApowBmodM(a, b, m):
  
    # Find a%m    
    ans = aModM(a, m)
    mul = ans
  
    # now multiply ans by b-1 times and take
    # mod with m
    for i in range(1,b):
        ans = (ans*mul) % m
          
    return ans
  
  
# Driver program to run the case
a = "987584345091051645734583954832576"
b, m = 3, 11
print (ApowBmodM(a, b, m))


C#




// C# program to find (a^b) mod m
// for a large 'a'
using System;
  
class GFG {
      
// utility function to calculate a%m
static int aModM(string s, int mod)
{
    int number = 0;
    for (int i = 0; i < s.Length; i++)
    {
          
        // (s[i]-'0') gives the digit
        // value and form the number
        number = (number * 10 );
        int x = (int)(s[i] - '0');
        number = number + x;
        number %= mod;
    }
    return number;
}
  
// Returns find (a^b) % m
static int ApowBmodM(string a, int b, 
                              int m)
{
      
    // Find a%m
    int ans = aModM(a, m);
    int mul = ans;
  
    // now multiply ans by b-1 times 
    // and take mod with m
    for (int i = 1; i < b; i++)
        ans = (ans * mul) % m;
  
    return ans;
}
  
// Driver Code
public static void Main()
{
    string a = "987584345091051645734583954832576";
    int b=3, m=11;
    Console.Write(ApowBmodM(a, b, m));
      
}
}
  
// This code is contributed by Sam007
  
  
  
  


PHP




<?php
// PHP program to find (a^b)
// mod m for a large 'a'
  
// utility function to 
// calculate a%m
function aModM($s, $mod)
{
    $number = 0;
    for ($i = 0; $i < strlen($s); $i++)
    {
          
        // (s[i]-'0') gives the digit
        // value and form the number
        $number = ($number * 10 + 
                  ($s[$i] - '0'));
        $number %= $mod;
    }
    return $number;
}
  
// Returns find (a^b) % m
function ApowBmodM($a, $b,$m)
{
      
    // Find a%m
    $ans = aModM($a, $m);
    $mul = $ans;
  
    // now multiply ans by 
    // b-1 times and take
    // mod with m
    for ($i = 1; $i < $b; $i++)
        $ans = ($ans * $mul) % $m;
  
    return $ans;
}
  
    // Driver code
    $a = "987584345091051645734583954832576";
    $b = 3;
    $m = 11;
    echo ApowBmodM($a, $b, $m);
    return 0;
  
// This code is contributed by nitin mittal.
?>


Javascript




<script>
  
// JavaScript program to find (a^b) mod m
// for a large 'a'
  
// Utility function to calculate a%m
function aModM(s, mod)
{
    let number = 0;
    for(let i = 0; i < s.length; i++)
    {
          
        // (s[i]-'0') gives the digit
        // value and form the number
        number = (number * 10 );
        let x = (s[i] - '0');
        number = number + x;
        number %= mod;
    }
    return number;
}
    
// Returns find (a^b) % m
function ApowBmodM(a, b, m)
{
      
    // Find a%m
    let ans = aModM(a, m);
    let mul = ans;
    
    // Now multiply ans by b-1 times 
    // and take mod with m
    for(let i = 1; i < b; i++)
        ans = (ans * mul) % m;
    
    return ans;
}
    
// Driver Code
let a = "987584345091051645734583954832576";
let b = 3, m = 11;
  
document.write(ApowBmodM(a, b, m));
  
// This code is contributed by souravghosh0416
  
</script>


Output

10

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

Auxiliary Space: O(1)

Efficient Approach: The above multiplications can be reduced to log b by using fast modular exponentiation where we calculate result by the binary representation of exponent (b). If the set bit is 1 we multiply current value of base to result and square the value of base for each recursive call.

Recursive Code:

C++14




// C++ program to find (a^b) mod m for a large 'a', with an
// efficient approach.
#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;
  
    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 * result) % m + m) % m;
    }
    return (result % m + m) % m;
}
  
int main()
{
    // String input as b is very large
    string a = "987584345091051645734583954832576";
    // String input as b is very large
    ll b = 3;
    ll m = 11;
    ll remainderA = MOD(a, m);
  
    cout << ModExponent(remainderA, b, m);
  
    return 0;
}


Java




// Java program to find (a^b) mod m for a large 'a', with an
// efficient approach.
public 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;
    }
    return res;
  }
  
  // Calculate the ModExponent of the given large number
  // 'a'
  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 % 2 != 0) {
      result = a % m;
      result = result * ModExponent(a, b - 1, m);
    }
    else {
      result = ModExponent(a, b / 2, m);
      result = ((result * result) % m + m) % m;
    }
    return (result % m + m) % m;
  }
  public static void main(String[] args)
  {
  
    // String input as a is very large
    String a = "987584345091051645734583954832576";
    long b = 3;
    long m = 11;
    long remainderA = MOD(a, m);
    System.out.println(ModExponent(remainderA, b, m));
  }
}
  
// The code is contributed by Gautam goel (gautamgoel962)


Python3




# Python3 program to find (a^b) mod m
# for a large 'a'
  
# Utility function to calculate a%m
def MOD(s, mod):
  
    res = 0
    for i in range(len(s)):
        res = (res * 10 + int(s[i])) % mod
    return res
  
# Returns find (a^b) % m
def ModExponent(a, b, m):
  
    if (a == 0):
        return 0
  
    elif (b == 0):
        return 1
  
    elif (b % 2 != 0):
        result = a % m
        result = result * ModExponent(a, b - 1, m)
  
    else:
        result = ModExponent(a, b / 2, m)
        result = ((result * result) % m + m) % m
  
    return (result % m + m) % m
  
# Driver Code
a = "987584345091051645734583954832576"
b = 3
m = 11
remainderA = MOD(a, m)
print(ModExponent(remainderA, b, m))
  
# This code is contributed by phasing17


C#




// C# program to find (a^b) mod m for a large 'a', with an
// efficient approach.
  
using System;
using System.Collections.Generic;
  
public 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;
        }
        return res;
    }
  
    // Calculate the ModExponent of the given large number
    // 'a'
    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 % 2 != 0) {
            result = a % m;
            result = result * ModExponent(a, b - 1, m);
        }
        else {
            result = ModExponent(a, b / 2, m);
            result = ((result * result) % m + m) % m;
        }
        return (result % m + m) % m;
    }
  
    // Driver Code
    public static void Main(string[] args)
    {
  
        // String input as a is very large
        string a = "987584345091051645734583954832576";
        long b = 3;
        long m = 11;
  
        // Function Call
        long remainderA = MOD(a, m);
        Console.WriteLine(ModExponent(remainderA, b, m));
    }
}
  
// The code is contributed by phasing17


Javascript




<script>
  
// JavaScript program to find (a^b) mod m
// for a large 'a'
  
// Utility function to calculate a%m
function MOD(s, mod)
{
       
    var res = 0;
    for (var i = 0; i < s.length; i++) {
      res = (res * 10 + (s[i] - '0')) % mod;
    }
    return res;
}
  
// Returns find (a^b) % m
function ModExponent(a, b, m)
{
      
    var result;
    if (a == 0) {
      return 0;
    }
    else if (b == 0) {
      return 1;
    }
    else if (b % 2 != 0) {
      result = a % m;
      result = result * ModExponent(a, b - 1, m);
    }
    else {
      result = ModExponent(a, b / 2, m);
      result = ((result * result) % m + m) % m;
    }
    return (result % m + m) % m;
}
  
      
// Driver Code
let a = "987584345091051645734583954832576";
let b = 3, m = 11;
var remainderA = MOD(a, m);
document.write(ModExponent(remainderA, b, m));
  
// This code is contributed by shinjanpatra.
</script>


Output

10

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

Auxiliary Space: O(log b)

Space Efficient Iterative Code:

C++14




// C++ program to find (a^b) mod m for a large 'a'
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
  
// utility function to calculate a%m and b%m
ll aModM(string s, ll mod)
{
    ll number = 0;
    for (ll i = 0; i < s.length(); i++)
    {
        // (s[i]-'0') gives the digit value and form
        // the number
        number = (number*10 + (s[i] - '0'));
        number %= mod;
    }
    return number;
}
  
// Returns find (a^b) % m
ll ApowBmodM(ll x, ll y,ll m)
{
    ll res=1;
  
    while(y)
    {
        if(y&1)
        res=(res*x)%m;
        y=y>>1;
        x=((x*x)%m+m)%m;
    }
    return (res%m+m)%m;
}
  
// Driver program to run the case
int main()
{
    string a = "987584345091051645734583954832576";
    ll b=3;
    ll m=11;
            // Find a%m
    ll x=aModM(a,m);
    cout << ApowBmodM(x,b,m);
    return 0;
}


Java




// Java program to find (a^b) mod m for a large 'a'
import java.util.*;
  
class GFG {
  
    // utility function to calculate a%m and b%m
    static long aModM(String s, long mod)
    {
        long number = 0;
        for (int i = 0; i < s.length(); i++) {
  
            // (s[i]-'0') gives the digit value and form
            // the number
            number = (number * 10 + (s.charAt(i) - '0'));
            number %= mod;
        }
        return number;
    }
  
    // Returns find (a^b) % m
    static long ApowBmodM(long x, long y, long m)
    {
        long res = 1;
  
        while (y > 0) {
            if ((y & 1) != 0)
                res = (res * x) % m;
            y = y >> 1;
            x = ((x * x) % m + m) % m;
        }
        return (res % m + m) % m;
    }
  
    // Driver program to run the case
    public static void main(String[] args)
    {
        String a = "987584345091051645734583954832576";
        long b = 3;
        long m = 11;
  
        // Find a%m
        long x = aModM(a, m);
        System.out.println(ApowBmodM(x, b, m));
    }
}
  
// This code is contributed by phasing17


Python3




# Python3 program to find (a^b) mod m for a large 'a'
  
# utility function to calculate a%m and b%m
def aModM(s, mod):
  
    number = 0;
    for i in range(len(s)):
        # int(s[i]) gives the digit value and form
        # the number
        number = (number * 10 + int(s[i]));
        number %= mod;
      
    return number;
  
  
# Returns find (a^b) % m
def ApowBmodM(x, y, m):
      
    res = 1;
  
    while (y > 0):
        if (y & 1):
            res = (res * x) % m;
        y = y >> 1;
        x = ((x * x) % m + m) % m;
      
    return (res % m + m) % m;
  
  
# Driver program to run the case
a = "987584345091051645734583954832576";
b = 3;
m = 11;
  
# Find a%m
x = aModM(a, m);
print(ApowBmodM(x, b, m));
  
# This code is contributed by phasing17


C#




// C# program to find (a^b) mod m for a large 'a'
using System;
  
class GFG
{
  
  // utility function to calculate a%m and b%m
  static long aModM(string s, long mod)
  {
    long number = 0;
    for (int i = 0; i < s.Length; i++)
    {
  
      // (s[i]-'0') gives the digit value and form
      // the number
      number = (number * 10 + (s[i] - '0'));
      number %= mod;
    }
    return number;
  }
  
  // Returns find (a^b) % m
  static long ApowBmodM(long x, long y, long m)
  {
    long res = 1;
  
    while (y > 0) {
      if ((y & 1) != 0)
        res = (res * x) % m;
      y = y >> 1;
      x = ((x * x) % m + m) % m;
    }
    return (res % m + m) % m;
  }
  
  // Driver program to run the case
  public static void Main(string[] args)
  {
    string a = "987584345091051645734583954832576";
    long b = 3;
    long m = 11;
  
    // Find a%m
    long x = aModM(a, m);
    Console.WriteLine(ApowBmodM(x, b, m));
  }
}
  
// This code is contributed by phasing17


Javascript




// JavaScript program to find (a^b) mod m for a large 'a'
  
// utility function to calculate a%m and b%m
function aModM(s, mod)
{
    let number = 0;
    for (var i = 0; i < s.length; i++) {
        // parseInt(s[i]) gives the digit value and form
        // the number
        number = (number * 10 + parseInt(s[i]));
        number %= mod;
    }
    return number;
}
  
// Returns find (a^b) % m
function ApowBmodM(x, y, m)
{
    let res = 1;
  
    while (y) {
        if (y & 1)
            res = (res * x) % m;
        y = y >> 1;
        x = ((x * x) % m + m) % m;
    }
    return (res % m + m) % m;
}
  
// Driver program to run the case
let a = "987584345091051645734583954832576";
let b = 3;
let m = 11;
  
// Find a%m
let x = aModM(a, m);
console.log(ApowBmodM(x, b, m));
  
  
// This code is contributed by phasing17


Output

10

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

Auxiliary Space: O(1)

Case: When both ‘a’ and ‘b’ are very large.

We can also implement the same approach if both ‘a’ and ‘b’ was very large. In that case, we would have first took mod of it with m using our aModM function. Then pass it to the above ApowBmodM recursive or iterative function to get the required result.

Recursive Code:

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;
      
    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()
{
     // String input as b is very large
    string a = "987584345091051645734583954832576";
    // String input as b is very large
    string b = "467687655456765756453454365476765";
    ll m = 1000000007;
    ll remainderA = MOD(a,m);
    ll remainderB = MOD(b,m);
   
    cout << ModExponent(remainderA, remainderB, m);
      
    return 0;
}


Java




/*package whatever //do not write package name here */
import java.io.*;
class GFG {
  
  // Reduce the number B to a small number
  // using Fermat Little.
  static long MOD(String num,int mod)
  {
    long res = 0;
  
    for(int i = 0; i < num.length(); i++)
    {
      res = (res * 10 + num.charAt(i) - '0') % mod;
    }
  
    return res;
  }
  
  static long ModExponent(long a,long b,long m){
    long result = 0;
  
    if(a == 0)
      return 0;
    else if(b == 0)
      return 1;
    else if((b&1) == 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;
  }
  
  public static void main (String[] args) {
  
    // String input as b is very large
    String a = "987584345091051645734583954832576";
  
    // String input as b is very large
    String b = "467687655456765756453454365476765";
    int m = 1000000007;
    long remainderA = MOD(a,m);
    long remainderB = MOD(b,m);
  
    System.out.println(ModExponent(remainderA, remainderB, m));
  
  }
}
  
// This code is contributed by aadityapburujwale


Python3




# Python3 program 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;
  
    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:
        b = b // 2
        result = ModExponent(a, b, m);
        result = ((result % m) * (result % m)) % m;
      
    return (result % m + m) % m;
  
  
# String input as b is very large
a = "987584345091051645734583954832576";
  
# String input as b is very large
b = "467687655456765756453454365476765";
  
m = 1000000007;
remainderA = (MOD(a, m));
remainderB = (MOD(b, m));
  
print(ModExponent(remainderA, remainderB, m));
  
# This code is contributed by phasing17


C#




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


Javascript




// JavaScript program to implement the approach
  
// Reduce the number B to a small number
// using Fermat Little
function MOD(num, mod)
{
    let res = 0;
  
    for (var i = 0; i < num.length; i++)
        res = (res * 10 + parseInt(num[i])) % mod;
  
    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 {
        b = b / 2n - (b % 2n);
        result = ModExponent(a, b, m);
        result = ((result % m) * (result % m)) % m;
    }
    return (result % m + m) % m;
}
  
// String input as b is very large
let a = "987584345091051645734583954832576";
  
// String input as b is very large
let b = "467687655456765756453454365476765";
  
let m = 1000000007;
let remainderA = BigInt(MOD(a, m));
let remainderB = BigInt(MOD(b, m));
  
console.log(ModExponent(remainderA, remainderB, BigInt(m)));
  
// This code is contributed by phasing17


Output

546081867

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

Auxiliary Space: O(log b)

Space Efficient Iterative Code:

C++14




// C++ program to find (a^b) mod m for a large 'a'
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
  
// utility function to calculate a%m and b%m
ll aModM(string s, ll mod)
{
    ll number = 0;
    for (ll i = 0; i < s.length(); i++) {
        // (s[i]-'0') gives the digit value and form
        // the number
        number = (number * 10 + (s[i] - '0'));
        number %= mod;
    }
    return number;
}
  
// Returns find (a^b) % m
ll ApowBmodM(string& a, string& b, ll m)
{
    ll res = 1;
  
    // Find a%m
    ll x = aModM(a, m);
  
    // Find b%m
    ll y = aModM(b, m);
  
    while (y) {
        if (y & 1)
            res = (res * x) % m;
        y = y >> 1;
        x = ((x % m) * (x % m)) % m;
    }
    return (res % m + m) % m;
}
  
// Driver program to run the case
int main()
{
    string a = "987584345091051645734583954832576";
    string b = "467687655456765756453454365476765";
    ll m = 1000000007;
    cout << ApowBmodM(a, b, m);
    return 0;
}


Java




/*package whatever //do not write package name here */
import java.io.*;
class GFG {
  
  // utility function to calculate a%m and b%m
  static long aModM(String s, long mod){
    long number = 0;
    for (int i = 0; i < s.length(); i++)
    {
  
      // (s.charAt(i)-'0') gives the digit value and form
      // the number
      number = (number * 10 + (s.charAt(i) - '0'));
      number %= mod;
    }
  
    return number;
  }
  
  // Returns find (a^b) % m
  static long ApowBmodM(String a, String b, long m)
  {
    long res = 1;
  
    // Find a%m
    long x = aModM(a, m);
  
    // Find b%m
    long y = aModM(b, m);
  
    while (y>0) {
      if ((y & 1)==1)
        res = (res * x) % m;
      y = y >> 1;
      x = ((x % m) * (x % m)) % m;
    }
    return (res % m + m) % m;
  }
  
  public static void main (String[] args) {
  
    String a = "987584345091051645734583954832576";
    String b = "467687655456765756453454365476765";
    long m = 1000000007;
    System.out.println(ApowBmodM(a, b, m));
  }
}
  
// This code is contributed by aadityapburujwale


Python3




# Python3 program to find (a^b) mod m for a large 'a'
  
# utility function to calculate a%m and b%m
  
  
def aModM(s, mod):
    number = 0
    for i in range(len(s)):
  
        # (s[i]-'0') gives the digit value and form
        # the number
        number = (number * 10 + (int(s[i])))
        number %= mod
  
    return number
  
  
# Returns find (a^b) % m
def ApowBmodM(a, b, m):
    res = 1
  
    # Find a%m
    x = aModM(a, m)
  
    # Find b%m
    y = aModM(b, m)
  
    while (y > 0):
        if (y & 1):
            res = (res * x) % m
        y = y >> 1
        x = ((x % m) * (x % m)) % m
  
    return (res % m + m) % m
  
  
# Driver program to run the case
a = "987584345091051645734583954832576"
b = "467687655456765756453454365476765"
m = 1000000007
print(ApowBmodM(a, b, m))
  
# This code is contributed by phasing17


Javascript




// JavaScript program to find (a^b) mod m for a large 'a'
  
// utility function to calculate a%m and b%m
function aModM(s, mod)
{
    let number = 0n;
    for (let i = 0; i < s.length; i++) {
        // (s[i]-'0') gives the digit value and form
        // the number
        number = (number * 10n + BigInt(parseInt(s[i])));
        number %= mod;
    }
    return number;
}
  
// Returns find (a^b) % m
function ApowBmodM(a, b, m)
{
    let res = 1n;
  
    // Find a%m
    let x = BigInt(aModM(a, m));
  
    // Find b%m
    let y = BigInt(aModM(b, m));
  
    while (y > 0n) {
        if (y & 1n)
            res = (res * x) % m;
        y = y >> 1n;
        x = ((x % m) * (x % m)) % m;
    }
    return (res % m + m) % m;
}
  
// Driver program to run the case
let a = "987584345091051645734583954832576";
let b = "467687655456765756453454365476765";
let m = 1000000007n;
console.log(ApowBmodM(a, b, m));
  
  
// This code is contributed by phasing17


C#




// C# program to find (a^b) mod m for a large 'a'
  
using System;
using System.Collections.Generic;
  
class GFG {
    // utility function to calculate a%m and b%m
    static long aModM(string s, long mod)
    {
        long number = 0;
        for (int i = 0; i < s.Length; i++) {
            // (s[i]-'0') gives the digit value and form
            // the number
            number = (number * 10 + (s[i] - '0'));
            number %= mod;
        }
        return number;
    }
  
    // Returns find (a^b) % m
    static long ApowBmodM(string a, string b, long m)
    {
        long res = 1;
  
        // Find a%m
        long x = aModM(a, m);
  
        // Find b%m
        long y = aModM(b, m);
  
        while (y != 0) {
            if ((y & 1) != 0)
                res = (res * x) % m;
            y = y >> 1;
            x = ((x % m) * (x % m)) % m;
        }
        return (res % m + m) % m;
    }
  
    // Driver program to run the case
    public static void Main(string[] args)
    {
        string a = "987584345091051645734583954832576";
        string b = "467687655456765756453454365476765";
        long m = 1000000007;
        Console.WriteLine(ApowBmodM(a, b, m));
    }
}
  
// This code is contributed by phasing17


Output

546081867

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

Auxiliary Space: O(1)

If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org.

 



Previous Article
Next Article

Similar Reads

Find (a^b)%m where 'b' is very large
Given three numbers a, b and m where 1&lt;=a, m&lt;=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: 8 2 ^ 3 % 17 = 8Input: a = 3, b = 100000000000000000000000000, m = 1000000007 Output: 835987331 Iterative Approach: According to Fermat's littl
11 min read
Find (a^b)%m where 'a' 'b' and 'c' is very large number
Given three numbers a, b, and m where10^9 ≤ a, b ≤ 10^9. Given very large ‘m’ containing 10^18+7 and m is a prime number, the task is to find (a ^ b) % m. Example: Input: a = "5541548454152524154", b = "946646454116451", M = 1e18+7Output: 588288874981883904 Input: a = "5454656454154", b = "5646546546465446", M = 1e18+7Output: 654515516062826496 App
14 min read
Recursive sum of digit in n^x, where n and x are very large
Given very large numbers n and x, we need to find the sum of digits of n^x such that : If n^x &lt; 10 digSum(n^x) = n^x Else digSum(n^x) = Sum(digSum(n^x)) Examples: Input : 5 4 Output : 4 We know 54 = 625 Sum of digits in 625 = 6 + 2 + 5 = 13 Sum of digits in 13 = 1 + 3 = 4 Input : 546878 56422 Output : 7 Prerequisite : Recursive sum of digits. Th
6 min read
Check whether a very large number of the given form is a multiple of 3.
Consider a very long K-digit number N with digits d0, d1, ..., dK-1 (in decimal notation; d0 is the most significant and dK-1 the least significant digit). This number is so large that it can't be given or written down explicitly; instead, only its starting digits are given and a way to construct the remainder of the number.Specifically, you are gi
13 min read
Print all 3 digit repeating numbers in a very large number
Given a very large number, print all the 3 digit repeating numbers with their frequency. If a 3 digit number appears more than once, print the number and its frequency. Example: Input: 123412345123456 Output: 123 - 3 times 234 - 3 times 345 - 2 times Input: 43243243 Output: 432 - 2 times 324 - 2 times 243 - 2 times Approach: Since the number is ver
6 min read
Series summation if T(n) is given and n is very large
Given a sequence whose nth term is T(n) = n2 - (n - 1)2 The task is to evaluate the sum of first n terms i.e. S(n) = T(1) + T(2) + T(3) + ... + T(n) Print S(n) mod (109 + 7).Examples: Input: n = 3 Output: 9 S(3) = T(1) + T(2) + T(3) = (12 - 02) + (22 - 12) + (32 - 22) = 1 + 3 + 5 = 9Input: n = 10 Output: 100 Approach: If we try to find out some ini
3 min read
Number of factors of very large number N modulo M where M is any prime number
Given a large number N, the task is to find the total number of factors of the number N modulo M where M is any prime number. Examples: Input: N = 9699690, M = 17 Output: 1 Explanation: Total Number of factors of 9699690 is 256 and (256 % 17) = 1Input: N = 193748576239475639, M = 9 Output: 8 Explanation: Total Number of factors of 9699690 is 256 an
8 min read
Print all K digit repeating numbers in a very large number
Given a very large number N in the form of a string and a number K, the task is to print all the K-digit repeating numbers whose frequency is greater than 1. Examples: Input: str = "123412345123456", K = 4 Output: 1234 - 3 2345 - 2 Explanation: The 4-digit numbers having frequency greater than 1 are 1234 and 2345. Input: N = 1432543214325432, K = 5
6 min read
XOR of very large Binary Numbers in range [L, R]
Given two binary strings L and R, the task is to find the xor from L to R. Length of the binary string is &lt; = 10e6. Examples: Input: L = 10, R = 100Output: 101Explanation: L = 2 and R = 4 in decimal system.Therefore, the xor will be 2^3^4 = 5(101). Input: L = 10, R = 10000Output: 10001 Naive Approach: The simplest approach to solve the problem i
15+ min read
Count of Unique elements in a very large sorted Array
Given a sorted array arr[] of size N, the task is to find the number of unique elements in this array. Note: The array is very large, and unique numbers are significantly less. i.e., (unique elements &lt;&lt;size of the array). Examples: Input: arr[] = {1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 5, 5, 7, 7, 8, 8, 9, 9, 10, 11, 12}Output: 10Explanation: 10 un
11 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg