我已经编写了一个代码来绕过大数字:问题是,有一个小问题,我似乎无法抓住它。它是准确的直到指数或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;
}
答案 0 :(得分:0)
我只看了你的代码并发现了一些事情:
功能:
unsigned long exponentV2(unsigned long a, unsigned long b, unsigned long m);
功能:
unsigned long add_mod(unsigned long a, unsigned long b, unsigned long m);
了解更多信息:Modular arithmetics and NTT (finite field DFT) optimizations
希望有所帮助