remainder operation rules

Today, I encountered a problem of displaying Int64  in As3 and JS . JS and AS only have the Number type, and the maximum supported integer is + 2^53, and ( −9007199254740992  to 9007199254740992) When the number exceeds the limit, it can only directly display the corresponding string, and cannot be converted by Number.   


I found an open source library on the Internet, which divides Int64 into two 32-bit numbers and stores them in the high and low fields of an object. Use highth * 4294967296 + low to represent the corresponding number; then implement the Int64.toString() method to display the corresponding string.

There is a problem with this method implemented by the open source library, and it cannot be calculated correctly. It took me a while to revise the question.


The general idea is to take the remainder of the number y=x%10; x= x/10; put the remainder y into the array, and if the result x is not 0, continue to repeat the above steps, and the reverse order of the obtained array is the desired character string;

When high and low are used to represent the number, the remainder operation is a little more complicated, and the following remainder operation rules need to be used



Modulo arithmetic is somewhat similar to the basic four arithmetic operations, except for division. Its rules are as follows:

 (a + b) % p = (a % p + b % p) % p 

(1) (a - b) % p = (a % p - b % p) % p 

(2) (a * b) % p = (a % p * b % p) % p 

(3) a ^ b % p = ((a % p)^b) % p 

(4) Associative law: ((a+b) % p + c) % p = (a + (b+c) % p) % p 

(5) ((a*b) % p * c)% p = (a * (b*c) % p) % p 

(6) Commutative law: (a + b) % p = (b+a) % p 

(7) (a * b) % p = (b * a) % p 

(8) 分配律: ((a +b)% p * c) % p = ((a * c) % p + (b * c) % p) % p 

important theorem

If a≡b (% p), then for any c, there are (a + c) ≡ (b + c) (%p);

(10) If a≡b (% p), then for any c, there are (a * c) ≡ (b * c) (%p);

(11) If a≡b (% p), c≡d (% p),

Then (a + c) ≡ (b + d) (%p),

(a - c) ≡ (b - d) (%p), 

(a * c) ≡ (b * d) (%p),

(a / c) ≡ (b / d) (%p);


// some key code

function div( n:unit):uint
{
    var MaxMod:uint = 0x100000000%n;
    var modHigh:uint = hight%n;
    var mod:uint = ((modHigh * MaxMod)%n + low%n)%n;
    hight = Math.floor( high/n);
    low = Math.floor((modHigh * 0x100000000 + low)/n );
    high += Math.floor( low/0x100000000);
    return mod;
}

// toString()里的处理部分
var digitChars:Array = [];
var tmp:Int64 = new UInt64(high, low);
if( high < 0)
{
    // 负数的话,时补码表示的;  反码再加1 得到原码
    tmp.bitwiseNot();
    tmp.add(1);
}
do
{
    var digit:uint = tmp.div( radix);
    digitChars.push( digit < 10 ? '0' : 'a').charCodeAt() + digit);
}
while( tmp.high != 0)

var flag:String = high < 0 ? "-" : "";
return flag + tmp.low.toString(radix) + String.fromCharCode.apply(String, digitChars.reverse());



Guess you like

Origin blog.csdn.net/tianhai110/article/details/78607191