Algorithm


problem link- https://www.spoj.com/problems/LASTDIG2/

LASTDIG2 - The last digit re-visited

 

Pappu was doing the work of his math class about three days but he is tired of make operations a lot and he should deliver his task tomorrow. His math’s teacher gives two numbers a and b. The problem consist in find the last digit of the potency of base a and index b. Help Pappu with his problem. You are given two integer numbers: the base a (number of digits d, such that 1 <= d <= 1000) and the index b (0 <= b <= 922*10^15). You have to find the last digit of a^b.

Input

The first line of input contains an integer t, the number of test cases (t <= 30). t test cases follow. For each test case will appear a and b separated by space.

Output

For each test case output an integer per line representing the result.

Example

Input:
3
3 10
6 2
150 53

Output:
9
6
0

 

Code Examples

#1 Code Example with Python Programming

Code - Python Programming

def power(a, b):
    if b == 0:
        return 1
    if b % 2 == 1:
        return power(a, b - 1) * a % 10
    half = power(a, b >> 1)
    return half * half % 10

T = int(input())
for i in range(T):
    a, b = map(int, raw_input().split())
    print(power(a % 10, b))
Copy The Code & Try With Live Editor

Input

x
+
cmd
3
3 10
6 2
150 53

Output

x
+
cmd
9
6
0

#2 Code Example with Java Programming

Code - Java Programming

import java.util.*;
import java.lang.Math.*;
import java.math.*;

class lastdig{

	public static void main(String[] args){

		Scanner scan = new Scanner(System.in);
		int testCases = scan.nextInt();
		BigInteger a = new BigInteger("0"); 
		BigInteger b = new BigInteger("0"); 
		BigInteger lastDigit = new BigInteger("0");

		for(int i = 0; i < testCases; i++){
			a = scan.nextBigInteger();
			b = scan.nextBigInteger();
			
			lastDigit = b.modPow(a, BigInteger.valueOf(10));

			System.out.println(lastDigit);
		} 

}}
Copy The Code & Try With Live Editor

Input

x
+
cmd
3
3 10
6 2
150 53

Output

x
+
cmd
9
6
0

#3 Code Example with C++ Programming

Code - C++ Programming

#include <iostream>
using namespace std;
#define ll long long
int bigmod(ll a, ll b)
{
	if(b==0) return 1;
	else{
		int x = bigmod(a, b/2);
		x = (x*x)%10;
		if(b%2==1) x = (x*a)%10;
		return x;
	}
}
int main() {
	ll t,a,b;
	string s;
	cin>>t;
	while(t--){
		cin>>s>>b;
		a = s[s.size()-1]-'0';
		cout<<bigmod(a,b)<<endl;
	}
	return 0;
} 
Copy The Code & Try With Live Editor

Input

x
+
cmd
3
3 10
6 2
150 53

Output

x
+
cmd
9
6
0
Advertisements

Demonstration


SPOJ Solution-The last digit re-visited-Solution in C, C++, Java, Python

Previous
SPOJ Solution - Test Life, the Universe, and Everything - Solution in C, C++, Java, Python