主編輯:有人請向我解釋如何修復operator /以便它能正常工作嗎?我意識到這種轉變並不總是正確的,例如10/3
,這將導致無限循環。那我該如何解決這個問題?如何正確實現`operator /`?
uint128_t operator/(uint128_t rhs){
// Save some calculations ///////////////////////
if (rhs == 0){
std::cout << "Error: division or modulus by zero" << std::endl;
exit(1);
}
if (rhs == 1)
return *this;
if (*this == rhs)
return uint128_t(1);
if ((*this == 0) | (*this < rhs))
return uint128_t(0, 0);
// //////////////////////////////////////////////
uint128_t copyn(*this), quotient = 0;
while (copyn >= rhs){
uint128_t copyd(rhs), temp(1);
// shift the divosr to match the highest bit
while (copyn > (copyd << 1)){
copyd <<= 1;
temp <<= 1;
}
copyn -= copyd;
quotient += temp;
}
return quotient;
}
這是正確的?
uint128_t operator/(uint128_t rhs){
// Save some calculations ///////////////////////
if (rhs == 0){
std::cout << "Error: division or modulus by zero" << std::endl;
exit(1);
}
if (rhs == 1)
return *this;
if (*this == rhs)
return uint128_t(1);
if ((*this == 0) | (*this < rhs))
return uint128_t(0);
uint128_t copyd(rhs);
// Checks for divisors that are powers of two
uint8_t s = 0;
while ((copyd.LOWER & 1) == 0){
copyd >>= 1;
s++;
}
if (copyd == 1)
return *this >> s;
// //////////////////////////////////////////////
uint128_t copyn(*this), quotient = 0;
copyd = rhs;
uint8_t n_b = 255, d_b = 0;
while (copyd){
copyd >>= 1;
d_b++;// bit size of denomiator
}
copyd = rhs;
while (n_b > d_b){
// get the highest bit of dividend at current step
n_b = 0;
uint128_t copycopyn(copyn);
while (copycopyn){
copycopyn >>= 1;
n_b++;
}
uint8_t highest_bit = n_b - d_b - 1;
copyn -= copyd << highest_bit;
quotient += uint128_t(1) << highest_bit;
}
if (n_b == d_b)
quotient++;
return quotient;
}
它似乎是正確的,但IM 10改裝時,不知何故得到隨機值很大,即使我的MOD功能只是
uint128_t operator%(uint128_t rhs){
return *this - (rhs * (*this/rhs));
}
當你通過代碼時,發生什麼情況? – 2011-06-17 03:04:04
你得到的輸出是什麼。你嘗試過flush()輸出嗎? – iammilind 2011-06-17 03:04:09
它凍結了。我無法找到問題的確切來源,儘管它似乎在'operator /'中。但正如我所說,儘可能慢,它不能///慢 – calccrypto 2011-06-17 03:05:32