给定两个整数A和B ,任务是计算2 2A % B 。
例子:
Input: A = 3, B = 5
Output: 1
223 % 5 = 28 % 5 = 256 % 5 = 1.
Input: A = 10, B = 13
Output: 3
方法:通过使用递归将问题分解为不溢出整数的子问题,可以有效地解决问题。
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.
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
#define ll long long
// Function to return 2^(2^A) % B
ll F(ll A, ll B)
{
// Base case, 2^(2^1) % B = 4 % B
if (A == 1)
return (4 % B);
else
{
ll temp = F(A - 1, B);
return (temp * temp) % B;
}
}
// Driver code
int main()
{
ll A = 25, B = 50;
// Print 2^(2^A) % B
cout << F(A, B);
return 0;
}
Java
// Java implementation of the above approach
class GFG
{
// Function to return 2^(2^A) % B
static long F(long A, long B)
{
// Base case, 2^(2^1) % B = 4 % B
if (A == 1)
return (4 % B);
else
{
long temp = F(A - 1, B);
return (temp * temp) % B;
}
}
// Driver code
public static void main(String args[])
{
long A = 25, B = 50;
// Print 2^(2^A) % B
System.out.println(F(A, B));
}
}
// This code is contributed by Ryuga
Python3
# Python3 implementation of the approach
# Function to return 2^(2^A) % B
def F(A, B):
# Base case, 2^(2^1) % B = 4 % B
if (A == 1):
return (4 % B);
else:
temp = F(A - 1, B);
return (temp * temp) % B;
# Driver code
A = 25;
B = 50;
# Print 2^(2^A) % B
print(F(A, B));
# This code is contributed by mits
C#
// C# implementation of the approach
class GFG
{
// Function to return 2^(2^A) % B
static long F(long A, long B)
{
// Base case, 2^(2^1) % B = 4 % B
if (A == 1)
return (4 % B);
else
{
long temp = F(A - 1, B);
return (temp * temp) % B;
}
}
// Driver code
static void Main()
{
long A = 25, B = 50;
// Print 2^(2^A) % B
System.Console.WriteLine(F(A, B));
}
}
// This code is contributed by mits
PHP
Javascript
输出:
46