Math 大数的Arduino模运算
我已经写了一个代码来处理这些大数字:问题是,有一个小问题我似乎无法理解。它是精确的,直到指数或b为2,然后是3-4,稍微偏离,然后是5-6,它才开始偏离真实答案Math 大数的Arduino模运算,math,modular,largenumber,Math,Modular,Largenumber,我已经写了一个代码来处理这些大数字:问题是,有一个小问题我似乎无法理解。它是精确的,直到指数或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 exponen
#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;
}
#包括
#包括
使用名称空间std;
无符号长模(无符号长b、无符号长n、无符号长m);
无符号长指数v2(无符号长a、无符号长b、无符号长m);
int main()
{
cout>1;//向左移动1位
}
返回结果;
}
无符号长加法模(无符号长a、无符号长b、无符号长m)
{
a=a%m;
b=b%m;
返回(a+b)%m;
}
我只是看了看你的代码,发现了几件事:
在功能上:
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);
- 我知道这个函数返回a^b mod m
- 在初始化中销毁指数(b=b%m),这将使结果无效!!!移开那条线
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);
- 您不处理溢出(如果a+b大于long怎么办?)
- 在这种情况下,(a+b)%m是错误的李>
- 在溢出的情况下,应该从结果中减去m*x,然后再减去模李>
- x必须和m*x一样大,以便消除溢出李>
- 所以(a+b)-(m*x)也适用于长变量
希望有帮助你得到了什么答案,你认为应该是什么?我一直在将它与wolfram alpha进行比较,并试图找出非常狡猾的错误。我现在不能给出数字,因为我正处于这一步,通过所有的步骤。你确信<代码>未签名的长< /代码>是代码应该运行的64位吗?(如果
mul_mod
类似于exponentV2
,则可能没有必要这样做,但如果它基本上是返回((a%m)*(b%m))%m;
)