Arduino模数算法的大数

时间:2012-10-06 13:09:16

标签: 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 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;
}

1 个答案:

答案 0 :(得分:0)

我只看了你的代码并发现了一些事情:

功能:

unsigned long exponentV2(unsigned long a, unsigned long b, unsigned long m);
  • 我知道这个函数返回一个^ b mod m
  • 在初始化中你销毁指数(b = b%m)这会使结果无效!!!删除该行

功能:

unsigned long add_mod(unsigned long a, unsigned long b, unsigned long m);
  • 你没有处理溢出(如果a + b大于长?怎么办?)
  • 在那种情况下(a + b)%m是错误的,......
  • 你应该在溢出的情况下从结果中减去m * x而不是模数。
  • x必须一样大,所以m * x几乎是消除溢出的长度......
  • 所以(a + b) - (m * x)也适合长变量

了解更多信息:Modular arithmetics and NTT (finite field DFT) optimizations

希望有所帮助