 # Spoj - Last Digit - RE

I know that modular exponentiation is enough to solve this problem but I came across a formula on Quora by Divanshu Garg ( http://qr.ae/R753zZ ). Using his formula the problem simply boils down to calculate and print pow(a%10,b%4)%10 but this approach is giving me Runtime error.
Here is my code.
http://ideone.com/Y5VQLJ
http://www.spoj.com/problems/LASTDIG/
Thanks for reading! #include <stdio.h>
#include <math.h>
int main()

{

``````    int t,a,b,res;

scanf("%d",&t);

while(t--)

{

scanf("%d%d",&a,&b);

if (b==0)

printf("1\n");

else

{

b=b%4;

res=pow(a,b);

if(b==0)

res=pow(a,4);

printf("%d\n",res%10);

}

}

return 0;
``````

}

Try this code, as you said, a%10, it will contain 1 digit only and b%4, it will also contain one digit only. So, you can use pow() function only.

I think the problem is with your modexpo() function. It gives runtime error because of the bitwise operator used. I changed b>>=1 to b/=2 and it gave Wrong answer on spoj but not Runtime error. So, change your modexpo() function. I better suggest you to use the code given above.

@h1ashdr@gon… i think you have not yet understood the concept (as mentioned by you on quora) well. For example let a = 2 and b=4, then ans is last digit of 2^4=16 i.e 6. But your code prints out 1 which is why it is WA. Understand that the answer for any a repeats after a max of 4 iterations. For eg for a=3 it repeats as 3, 9, 7 and 1 while for a=6, it repeats as 6,6,6,6 so after taking b%4 which gives answer in the range [0,3] doesn’t actually give the correct answer when b is a multiple of 4. So, as i wrote my code above consider the code which checks explicitly for the case when b%4=0, just add this condition and i think your code will run fine now…

Happy coding.

Simply pow(a%10,b%4) gives WA. Tried a simple implementation here,