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.
Problem link :
Thanks for reading! :slight_smile:

#include <stdio.h>
#include <math.h>
int main()


    int t,a,b,res;





        if (b==0)











    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.

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

@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.