主编辑:有人请向我解释如何修复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