I'd like to implement a 256bit integer type for working with large numbers. That being said, I cannot use the default arithmetic operators so I have to reimplement them with bitwise operations.
So far I have most of them working and tested individually, but I can't get past division.
I'm doing this partly for learning purposes, so while bignum libraries are welcome, they aren't something I'm looking for at the moment.
I modified a code from an another answer, here: https://stackoverflow.com/a/19780781/1619594
Int_256 operator/(Int_256 dividend, const Int_256 &divisor) {
Int_256 quotient = { 0, 0, 0, 0 };
int nPos = -1;
Int_256 tempDivisor = divisor;
while (tempDivisor < dividend) {
tempDivisor = tempDivisor << 1;
nPos ++;
}
tempDivisor = tempDivisor >> 1;
while (nPos > -1) {
if (dividend >= tempDivisor) {
quotient = quotient + (1 << nPos);
dividend = dividend - tempDivisor;
}
tempDivisor = tempDivisor >> 1;
nPos -= 1;
}
Int_256 remaining = dividend;
return quotient;
}
Everything's supposed to be unsigned, in fact the "Int_256" is just 4 64bit unsigned integers together.
The problem is that while it sometimes will work fine, but at other times, it won't.
E.g.: 10/5 == 1, with a remainder of 5, and 8/2 == 3, with a remainder of 2, etc.
However 35/5 and 10/2 will give correct results.
Does anyone know what the issue could be that I missed?
Update: Here's the whole code as it was requested: http://fecka.ddns.net/gogs/fecka/int256test
It is incomplete and messy, there are probably a lot of things wrong with it, a minute ago I found out, that even multiplying won't work properly, so any help would be much appreciated.