首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用于大数的Arduino模算法

用于大数的Arduino模算法
EN

Stack Overflow用户
提问于 2012-10-06 13:09:15
回答 1查看 1.6K关注 0票数 1

我已经写了一个代码来绕开大数字:问题是,有一个小小的问题,我似乎无法理解它。它是精确的,直到指数或b是2,然后是3-4,它稍微偏离,然后5-6,它只是开始偏离真实的答案。

代码语言:javascript
复制
#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;
}
EN

回答 1

Stack Overflow用户

发布于 2013-09-03 13:55:50

我只是看了一下您的代码,很少注意到:

职能:

代码语言:javascript
复制
unsigned long exponentV2(unsigned long a, unsigned long b, unsigned long m);
  • 我知道这个函数返回a^b mod m
  • 在初始化时,您破坏指数(b=b%m)这个无效的结果!移除那条线

职能:

代码语言:javascript
复制
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)也适用于长变量

要了解更多的信息,请看下面的内容:Modular arithmetics and NTT (finite field DFT) optimizations

希望它能帮上忙

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12760075

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档