I was trying to solve this problem: http://www.spoj.com/problems/LASTDIG/ where it takes a base and exponent and I have to output the last digit of the result of theexponentiation, but online judge says that my program gives wrong answers though for typical test cases, my outputs are right.
N.B.: I have to use Fast Modular Exponentiation algorithm, here's a nice explanation for that: https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/fast-modular-exponentiation
using System;
public class Test
{
public static void Main()
{
int val = Convert.ToInt32(Console.ReadLine());
for (int i=0; i<val; i++ )
{
string input = Console.ReadLine();
int a = Convert.ToInt32(input.Split()[0]);
int b = Convert.ToInt32(input.Split()[1]);
if (a==0)
{
Console.WriteLine(0);
} else if(b==0)
{
Console.WriteLine(1);
} else {
a=a%10;
string bToBinary=Convert.ToString(b, 2);
double temp = 1;
for(int j=bToBinary.Length-1, k=0; j>=0; j--, k++)
{
if (bToBinary[j] == '1')
{
temp = temp*(Math.Pow(a, Math.Pow(2, k)));
}
}
Console.WriteLine(temp%10);
}
}
}
}
Sample Input:
4
3 10
6 2
14 11
1 0
Output from this program:
9
6
4
1