我对C++相当陌生,并且一直在试图编写一个程序来处理非常大的输入数字(7e + 11 ish)。它可以在很少的数字下正常工作,但不适用于这些大数字。我意识到这是因为非常大的数字不适合int,但是当我尝试像__int64,long long int,unsigned long long int和uint64_t这样的其他类型时,函数“nextsmallestfactor”不起作用(它通常输出0和因此在除以a,输出时触发错误)。我应该使用什么?这段代码应该占用很大的数字,每次重复将其分为最小的数字,并在最后输出一个最高的素数因子。在C++中使用非常大的数字的函数
#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;
}
非常感谢您的帮助。
int的最大尺寸是2,147,483,647 – andre 2014-08-29 19:44:44
nextsmallestfactor()中的所有代码路径都不会返回一个值...但是如果将条件更改为factor <= numbertofactorise,那么您应该很好,因为x%x == 0 for所有值,if语句在一次迭代中必须为真 – clcto 2014-08-29 19:44:51
You h要使用更大的'int'类型,比如'int64_t'。至于“我的功能不起作用”......呃,你必须弄清楚什么不起作用。无论你的函数有什么问题,它们都与你使用'int64_t'的事实无关。 – AnT 2014-08-29 19:45:29