我對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