我正在嘗試實作除法二進制演算法。
該代碼有一些邏輯錯誤,我仍在試圖弄清楚如何修復它們。
myuint operator/(const myuint<T>& x)
{
myuint<T> temp;
myuint<T> result;
int count = 0;
for(int i = bits.size() - 1 ; i >= 0; --i)
{
temp.bits.push_back(bits[i]);
if(temp >= x)
{
count ;
*this = *this - x;
temp = 0;
}
}
result = count;
return result;
}
我還為除法多載了 >=、> 和 == 運算子。
邏輯問題很可能在 for 回圈中。我該怎么辦?謝謝
可以從這里訪問完整代碼
== 編輯
我想要達到的就是這個。*這是 10100(十進制的 20)x 是 100(十進制的 4)
- 獲取第一個位 (1)。
- 將其與 x 進行比較
- 如果該位大于 x 的值,count ,從 *this 中減去 x。然后再次啟動不同的 *this 大小的回圈。
- 如果位很小,那么我們移動到它旁邊的位,所以現在我們有 2 位 (10),我們將它與 x 進行比較。
- 然后我回傳 count 的值,它表示這個分割數達到 0。
uj5u.com熱心網友回復:
不是一個完整的答案,但這是您需要實作的演算法:
myuint div(const myuint& x, const myuint& y)
{
if (y == 0)
throw "division by zero";
myuint res = 0;
myuint one = 1;
unsigned int xLength = x.bitLength();
unsigned int yLength = y.bitLength();
while (xLength > yLength)
{
res = one << (xLength - yLength - 1);
x -= y << (xLength - yLength - 1);
xLength = x.bitLength();
}
if (x >= y)
return res 1;
return res;
}
uj5u.com熱心網友回復:
所以,我找到了一個如何繞過二進制除法的簡單實作。
這個想法是你從 RHS 中減去 LSH,直到 LHS 小于 RHS 并在你從 LSH 中減去 RHS 的多次保持不變。
myuint operator/(const myuint<T>& x)
{
myuint<T> LHS = *this;
myuint<T> RHS = x;
myuint<T> result;
int count = 0;
bool flag = true;
if(LHS == RHS)
{
return 1;
}
else
{
do
{
if(LHS >= RHS)
{
LHS = LHS - RHS;
count ;
}
else if(LHS < RHS)
{
flag = false;
}
}while(flag);
}
result = count;
return result;
}
這可能不是最有效的方法。但它可以完成作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/412635.html
標籤:
