📜  求2 ^(2 ^ A)%B

📅  最后修改于: 2021-06-26 20:06:52             🧑  作者: Mango

给定两个整数AB ,任务是计算2 2A %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

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。