c++中long-long的模运算

modulus operations on long long in c++

本文关键字:运算 long-long c++      更新时间:2023-10-16

我正在研究大数字的素数分解(主要是项目3@project Euler。我需要对声明为long-long的数字使用模。每次我试图对那个巨大的数字进行模运算时,我都会得到一个浮点异常。如有任何帮助,我们将不胜感激。谢谢。

我已经通过gdb运行了这个,看看发生了什么。下面是我的代码。这是一个非常粗略的逻辑请不要给我这个问题的答案。我很乐意接受帮助,让这件事变得更好,只是请不要直截了当地回答我。谢谢:)

long factor(long number) {
  string br = "nr";
  long x = 0;
  /*this modulus variable is an attempt
  to move the answer into a long long container
  to see if that solves my floating point exception,
  it didn't*/
  long long modulus;
  while(x <= number) {
    modulus = number % x;
    if(modulus == 0) {
      cout << number/x << br;
      return factor(number/x);
    }//if number % x
    else {
      return x;
    }//else
    x++;
  }//while
}//factor

不要试图通过0进行mod,它是未定义的!这样做将导致除以零的错误。

long x = 0;
modulus = number % x; // x is 0 here and thus not valid

根据维基百科关于模块操作的文章,我的答案可以进一步扩展

a模0在大多数系统中都是未定义的,尽管有些系统确实将其定义为a。

从开始

long x = 1 ;

以避免被零除。

相关文章: