给定正N ,任务是找到7 N的后两位。
例子:
Input: N = 5
Output: 07
Explanation:
The value of 75 = 7 * 7 * 7 * 7 * 7 = 8507
Therefore, the last two digits are 07.
Input: N = 12
Output: 01
Explanation:
The value of 712 = 13841287201
Therefore, the last two digits are 01.
方法:本文以对数时间复杂度讨论了找到X Y的最后K个数字的一般方法。在本文中,我们将讨论固定时间解决方案。
下面是用于7 N对于N的一些值的值的观察:
71 = 7 last two digit = 07
72 = 49 last two digit = 49
73 = 243 last two digit = 43
74 = 2401 lasr two digit = 01
75 = 16807 last two digit = 07
76 = 117649 last two digit = 49
77 = 823543 last two digit = 43
78 = 5764801 last two digit = 01
基于以上观察,我们有以下几种情况:
- 如果7的最后两位N = 07,则N = 4K + 3。
- 如果N = 4K + 2,则7中的最后两位N = 49。
- 如果N = 4K + 1,则7中的最后两位N = 43。
- 如果7的最后两位N = 01,则N = 4K。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to find the last
// two digits of 7^N
string get_last_two_digit(int N)
{
// Case 4
if (N % 4 == 0)
return "01";
// Case 3
else if (N % 4 == 1)
return "07";
// Case 2
else if (N % 4 == 2)
return "49";
// Case 1
return "43";
}
// Driver Code
int main()
{
// Given Number
int N = 12;
// Function Call
cout << get_last_two_digit(N);
return 0;
}
Java
// Java program for the above approach
import java.io.*;
import java.util.*;
class GFG{
// Function to find the last
// two digits of 7^N
public static String get_last_two_digit(int N)
{
// Case 4
if (N % 4 == 0)
return "01";
// Case 3
else if (N % 4 == 1)
return "07";
// Case 2
else if (N % 4 == 2)
return "49";
// Case 1
return "43";
}
// Driver code
public static void main(String[] args)
{
int N = 12;
// Function Call
System.out.println(get_last_two_digit(N));
}
}
// This code is contributed by grand_master
Python3
# Python3 program for the above approach
# Function to find the last
# two digits of 7 ^ N
def get_last_two_digit(N):
# Case 4
if (N % 4 == 0):
return "01";
# Case 3
elif (N % 4 == 1):
return "07";
# Case 2
elif (N % 4 == 2):
return "49";
# Case 1
return "43";
# Driver Code
# Given number
N = 12;
# Function call
print( get_last_two_digit(N))
# This code is contributed by grand_master
C#
// C# program for the above approach
using System;
namespace GFG{
class GFG{
// Function to find the last
// two digits of 7^N
public static String get_last_two_digit(int N)
{
// Case 4
if (N % 4 == 0)
return "01";
// Case 3
else if (N % 4 == 1)
return "07";
// Case 2
else if (N % 4 == 2)
return "49";
// Case 1
return "43";
}
// Driver code
public static void Main()
{
// Given number
int N = 12;
// Function Call
Console.Write(get_last_two_digit(N));
}
}
}
// This code is contributed by grand_master
输出:
01
时间复杂度: O(1)
辅助空间: O(1)