简体   繁体   中英

Remainder of euclidean division algorithm

I use JavaScript with my own BigInteger library, I have a problem with the complexity of the mod function.

// r = big1 - (big2 * (big1/big2))
function mod(big1, big2){
return subs(big1, multiply(big2, divide(big1,big2))); 
}

//r = b1 % b2

a different approach is to operate modulus by parts (say your limit for a number is 9 digits per number and say b2 < 100):

  1. Starting from the leftmost digit of b1, construct a number using the first 9 digits and call it N.
  2. Calculate N mod b2, giving a result in the range 00 to 99 (remember the example is b2 < 100).
  3. Construct a new 9-digit N by concatenating above result (step 2) with the next 7 digits of b1. If there are fewer than 7 digits remaining in b1 but at least one, then construct a new N, which will have less than 9 digits, from the above result (step 2) followed by the remaining digits of b1
  4. Repeat steps 2–3 until all the digits of b1 have been processed

final outcome is b1%b2. If also b2 is very large this will not work, but if only b1 is very large you can treat it is a string for the purpose of the algorithm.

coding it should be easy with iteration since you can know the number of iterations beforehand, don't even need recursion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM