2014-08-29 135 views
-1

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

}

非常感謝您的幫助。

+1

int的最大尺寸是2,147,483,647 – andre 2014-08-29 19:44:44

+0

nextsmallestfactor()中的所有代碼路徑都不會返回一個值...但是如果將條件更改爲factor <= numbertofactorise,那麼您應該很好,因爲x%x == 0 for所有值,if語句在一次迭代中必須爲真 – clcto 2014-08-29 19:44:51

+1

You h要使用更大的'int'類型,比如'int64_t'。至於「我的功能不起作用」......呃,你必須弄清楚什麼不起作用。無論你的函數有什麼問題,它們都與你使用'int64_t'的事實無關。 – AnT 2014-08-29 19:45:29

回答

4

問題是,如果你給你的函數一個素數,那麼代碼永遠不會返回一個值,因此會產生未定義的行爲。讓我們寫出來的循環迭代,當我們輸入一個素數:

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; 
+0

我在這裏創建了一個工作示例:http://ideone.com/WivvOP – clcto 2014-08-29 19:55:49

+0

非常感謝。你可愛的ASCII藝術幫助我理解和解決問題 - 我只需要將int更改爲int64_t,並將因子 2014-08-30 09:56:48

1

如果你想寫一些C++代碼能夠處理巨大的數字(所有數字),你需要bignums。那麼我建議你使用一些現有的bignum庫,如GMPLIB;你將能夠計算例如具有所有數字的1000的階乘。

不要試圖重塑自己的bignum庫;因爲複雜的底層算法(比天真的算法更有效)很難理解(和重新發明)。

某些語言和實現(例如Common Lisp的SBCL)具有內置的bignums。