给定数字n,我们需要找到2 n的最后一位
Input : n = 4
Output : 6
The last digit in 2^4 = 16 is 6
Input : n = 11
Output : 8
The last digit in 2^11 = 2048 is 8
一个朴素的解决方案是先计算幂= pow(2,n),然后使用幂%10查找幂的最后一位。这种解决方案效率低下,并且对于n稍大,还存在整数算术问题。
一个有效的解决方案基于以下事实:如果我们保留2 ^ 0(即1),则末位数字将以4为周期重复。2的幂(从2 ^ 1开始)为2、4、8、16、32、64、128 ,256、512、1024、2048,…
我们可以注意到最后的数字是2、4、8、6、2、4、8、6、2、4、8…
1)我们计算rem = n%4。请注意,最后一个rem将具有从0到3的值。
2)根据余数返回最后一位。
Remainder Last Digit
1 2
2 4
3 8
0 6
插图:让n = 11,rem = n%4 =3。2 ^ 3中的最后一位为8,与2 ^ 11的最后一位相同。
C++
// C++ program to find last digit in a power of 2.
#include
using namespace std;
int lastDigit2PowerN(int n)
{
// Corner case
if (n == 0)
return 1;
// Find the shift in current cycle
// and return value accordingly
else if (n % 4 == 1)
return 2;
else if (n % 4 == 2)
return 4;
else if (n % 4 == 3)
return 8;
else
return 6; // When n % 4 == 0
}
// Driver code
int main()
{
for (int n = 0; n < 20; n++)
cout << lastDigit2PowerN(n) << " ";
return 0;
}
Java
// Java program to find last
// digit in a power of 2.
import java.io.*;
import java.util.*;
class GFG{
static int lastDigit2PowerN(int n)
{
// Corner case
if (n == 0)
return 1;
// Find the shift in current cycle
// and return value accordingly
else if (n % 4 == 1)
return 2;
else if (n % 4 == 2)
return 4;
else if (n % 4 == 3)
return 8;
else
return 6; // When n % 4 == 0
}
// Driver code
public static void main(String[] args)
{
for (int n = 0; n < 20; n++)
System.out.print(lastDigit2PowerN(n) + " ");
}
}
// This code is contributed by coder001
Python3
# Python3 program to find last
# digit in a power of 2.
def lastDigit2PowerN(n):
# Corner case
if n == 0:
return 1
# Find the shift in current cycle
# and return value accordingly
elif n % 4 == 1:
return 2
elif n % 4 == 2:
return 4
elif n % 4 == 3:
return 8
else:
return 6 # When n % 4 == 0
# Driver code
for n in range(20):
print(lastDigit2PowerN(n), end = " ")
# This code is contributed by divyeshrabadiya07
C#
// C# program to find last
// digit in a power of 2.
using System;
class GFG{
static int lastDigit2PowerN(int n)
{
// Corner case
if (n == 0)
return 1;
// Find the shift in current cycle
// and return value accordingly
else if (n % 4 == 1)
return 2;
else if (n % 4 == 2)
return 4;
else if (n % 4 == 3)
return 8;
else
return 6; // When n % 4 == 0
}
// Driver code
public static void Main(string[] args)
{
for (int n = 0; n < 20; n++)
{
Console.Write(lastDigit2PowerN(n) + " ");
}
}
}
// This code is contributed by rutvik_56
输出:
1 2 4 8 6 2 4 8 6 2 4 8 6 2 4 8 6 2 4 8
时间复杂度:O(1)
辅助空间:O(1)
我们可以将其归纳为任何输入数字吗?请参阅查找a ^ b的最后一位以获取大数