我写了一个代码来绕过大数字:问题是,有一个小问题我似乎无法抓住它。它是准确的,直到指数或 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;
}