1
我寫了一個代碼來繞過大數字:問題是,有一個輕微的問題,我似乎無法捕捉它。直到指數纔是準確的,或者b是2,然後是3-4,稍微偏離,然後5-6它剛剛開始偏離真實答案。Arduino模塊化算術大數
#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;
}
你什麼答案,你怎麼看它應該是什麼? – Beta
我一直在比較它與沃爾夫拉姆阿爾法,並試圖追查非常狡猾的錯誤。我現在無法給出數字,因爲我處於這個過程中,逐步完成所有事情。 –
你確定無處不在的代碼應該運行的時候是'unsigned long'是64位嗎? (如果'mul_mod'類似於'exponentV2',這可能不是必須的,但如果它基本上是'return((%m)*(b%m))%m;'。 –