在C 中實作BigInt 類別
在C 中,當處理大於long int 的數字時,建立自訂“大整數”類。不要依賴外部實現,而是考慮創建自己的實現來更深入地理解這些概念。
資料結構
一種簡單的方法是將數字儲存為字串,將其分解為更小的數字(例如數字),並將它們放入一個數組中。這簡化了比較運算,但引起了對加法和乘法等運算的擔憂。
演算法概述
對於這些運算,考慮整數的二元性質是有益的。以實作加法運算子 (=) 為例,迭代每個數字對,然後將它們相加。如果結果溢位 BaseType,則將超出的部分轉入下一位。
程式碼範例
template< class BaseType > BigInt< BaseType >& BigInt< BaseType >::operator += (BigInt< BaseType > const& operand) { BT count, carry = 0; for (count = 0; count < std::max(value_.size(), operand.value_.size(); count++) { BT op0 = count < value_.size() ? value_.at(count) : 0, op1 = count < operand.value_.size() ? operand.value_.at(count) : 0; BT digits_result = op0 + op1 + carry; if (digits_result-carry < std::max(op0, op1) { BT carry_old = carry; carry = digits_result; digits_result = (op0 + op1 + carry) >> sizeof(BT)*8; // NOTE [1] } else carry = 0; } return *this; }
實作說明
其他運算子
重複這種減法、乘法和除法的演算法方法。實施標準運算符,如
結論
建立自訂 BigInt 類別是一項具有挑戰性但有益的練習。遵循此處概述的步驟可以幫助您實現一個強大且高效的類,用於處理 C 中的任意大整數。
以上是如何在 C 中實作 BigInt 類別來處理任意大整數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!