大きな数字を回避するためのコードを書きました。指数または b が 2 になるまでは正確ですが、3 ~ 4 になるとわずかにずれ、5 ~ 6 になると真の答えからずれ始めます。
#include <iostream>
#include <conio.h>
using namespace std;
unsigned long mul_mod(unsigned long b, unsigned long n, unsigned long m);
unsigned long exponentV2(unsigned long a, unsigned long b, unsigned long m);
int main()
{
cout << exponentV2(16807, 3, 2147483647);
getch();
}
unsigned long exponentV2(unsigned long a, unsigned long b, unsigned long m)
{
unsigned long result = (unsigned long)1;
unsigned long mask = b; // masking
a = a % m;
b = b % m;
unsigned long pow = a;
// bits to exponent
while(mask)
{
//Serial.print("Binary: "); // If you want to see the binary representation, uncomment this and the one below
//Serial.println(maskResult, BIN);
//delay(1000); // If you want to see this in slow motion
if(mask & 1)
{
result = (mul_mod(result%m, a%m, m))%m;
//Serial.println(result); // to see the step by step answer, uncomment this
}
a = (mul_mod((a%m), (a%m), m))%m;
//Serial.print("a is ");
//Serial.println(a);
mask = mask >> 1; // shift 1 bit to the left
}
return result;
}
unsigned long add_mod(unsigned long a, unsigned long b, unsigned long m)
{
a = a%m;
b = b%m;
return (a+b)%m;
}