Find 2^(2^A) % B
Last Updated :
29 Dec, 2022
Given two integers A and B, the task is to calculate 22A % B.
Examples:
Input: A = 3, B = 5
Output: 1
223 % 5 = 28 % 5 = 256 % 5 = 1.
Input: A = 10, B = 13
Output: 3
Approach: The problem can be efficiently solved by breaking it into sub-problems without overflow of integer by using recursion.
Let F(A, B) = 22A % B.
Now, F(A, B) = 22A % B
= 22 * 2A – 1 % B
= (22A – 1 + 2A – 1) % B
= (22A – 1 * 22A – 1) % B
= (F(A – 1, B) * F(A – 1, B)) % B
Therefore, F(A, B) = (F(A – 1, B) * F(A – 1, B)) % B.
The base case is F(1, B) = 221 % B = 4 % B.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
#define ll long long
ll F(ll A, ll B)
{
if (A == 1)
return (4 % B);
else
{
ll temp = F(A - 1, B);
return (temp * temp) % B;
}
}
int main()
{
ll A = 25, B = 50;
cout << F(A, B);
return 0;
}
|
Java
class GFG
{
static long F( long A, long B)
{
if (A == 1 )
return ( 4 % B);
else
{
long temp = F(A - 1 , B);
return (temp * temp) % B;
}
}
public static void main(String args[])
{
long A = 25 , B = 50 ;
System.out.println(F(A, B));
}
}
|
Python3
def F(A, B):
if (A = = 1 ):
return ( 4 % B);
else :
temp = F(A - 1 , B);
return (temp * temp) % B;
A = 25 ;
B = 50 ;
print (F(A, B));
|
C#
class GFG
{
static long F( long A, long B)
{
if (A == 1)
return (4 % B);
else
{
long temp = F(A - 1, B);
return (temp * temp) % B;
}
}
static void Main()
{
long A = 25, B = 50;
System.Console.WriteLine(F(A, B));
}
}
|
PHP
<?php
function F( $A , $B )
{
if ( $A == 1)
return (4 % $B );
else
{
$temp = F( $A - 1, $B );
return ( $temp * $temp ) % $B ;
}
}
$A = 25;
$B = 50;
echo F( $A , $B );
|
Javascript
<script>
function F(A, B)
{
if (A == 1)
return (4 % B);
else
{
var temp = F(A - 1, B);
return (temp * temp) % B;
}
}
var A = 25, B = 50;
document.write( F(A, B));
</script>
|
Time Complexity: O(A)
Auxiliary Space: O(A), due to recursive call stack
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...