C++中数字很大的函数

Functions with very big numbers in C++

本文关键字:函数 数字 C++      更新时间:2023-10-16

我对C++还很陌生,一直在尝试编写一个程序来处理非常大的输入数字(7e+11ish)。它适用于小数字,但不适用于这些大数字。我意识到这是因为非常大的数字不适合int,但当我尝试其他类型,如__int64、long-long-int、unsigned long-longint和uint64_t时,函数"nextsmallstactor"不起作用(它通常输出0,因此在除以输出a时会触发错误)。那我该用什么?这个代码应该取一个大的数字,重复地用每次除以它的最小数字除以它,并在最后输出最高素数a。

#include <iostream>
using namespace std;
int numberToFactorise = 700000000000;
int nextsmallestfactor(int numbertofactorise){
    for (int factor = 2; factor < numbertofactorise; factor++){
    if (numbertofactorise%factor == 0){
        return factor;
    }
}
}
int main(){
    int quotient = numberToFactorise;
    int a=1;
    while (quotient > 1){
        a = nextsmallestfactor(quotient);
        quotient = quotient / a;
    };
    cout << a;
cout << endl;
system("PAUSE");
return 0;

}

非常感谢您的帮助。

问题是,如果给函数一个素数,那么代码实际上永远不会返回值,因此会产生未定义的行为。当我们输入素数时,让我们写出循环的迭代:

nextsmallestfactor( 5 ):
      factor  |  numbertofactorise % factor
       ----------------------------
        2     |   5%2 = 1
        3     |   5%3 = 2
        4     |   5%4 = 1 
 END (no return)

如果您将条件更改为检查系数并包括numbertofactorize,则会执行以下操作:

nextsmallestfactor( 5 ):
      factor  |  numbertofactorise % factor
       ----------------------------
        2     |   5%2 = 1
        3     |   5%3 = 2
        4     |   5%4 = 1 
        5     |   5%5 = 0  ---> return 5;

如果你想编写一些能够处理巨大数字(及其所有数字)的C++代码,你需要bignum。然后我建议您使用一些现有的bignum库,如GMPLIB;你将能够计算例如1000的阶乘及其所有数字。

不要试图重塑你自己的bignum库;因为复杂的底层算法(比天真的算法更有效)很难理解(也很难重新发明)。

一些语言和实现(例如Common Lisp的SBCL)具有内置bignum。

相关文章: