LASTDIG - The last digit
Nestor 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 him two numbers a and b. The problem
consist of finding the last digit of the potency of base a and index b.
Help Nestor with his problem. You are given two integer numbers: the
base a (0 <= a <= 20) and the index b (0 <= b <=
2,147,483,000), a and b both are not 0. You have to find the last digit
of ab.
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: 2 3 10 6 2 Output: 9 6
The link to this problem is:
The approach is very simple
Note: If the last digit in the base is 0 or 1 or 6 or 5 then any power of that base is same as base
for others we can use the technique as shown in the code.You can simply understand the problem by writing some examples in paper.
Solution in cpp
#include <iostream>
using namespace std;
int main() {
long int i,j,n,a,b;
cin>>n;
for( i=0;i<n;i++)
{
cin>>a>>b;
long int mod = b%4;
long int po = a%10;
if(b==0)
cout<<"1"<<endl;
else if(a==0)
cout<<"0"<<endl;
else if(po==1||po==5||po==6||po==0)
cout<<po<<endl;
else{
if(mod==1)
{
cout<<(po%10);
}
else if(mod==2)
{
cout<<((po*po)%10);
}
else if(mod==3)
{
cout<<((po*po*po)%10);
}
else{
cout<<((po*po*po*po)%10);
}
cout<<endl;
}
}
}
No comments:
Post a comment