Division is not the manual algorithm to calculate, the basic idea is to do subtraction repeatedly, see from the divisor of the most can subtract how many divisor, quotient is how much.
Division function:
- If the former value is less than the latter directly returns zero
- Do subtraction, do not need a minus, you can use the divisor *10^n as the base to reduce
1 functionDivision (A, B) {/*Enter a large number of two string types*/2 3A =a.tostring ();4 5b =b.tostring ();6 7 varSign = ";8 9 if(A.indexof ('-') >= 0 && b.indexof ('-') < 0){Ten OneSign = '-'; A -A = A.SUBSTR (1); - } the Else if(A.indexof ('-') < 0 && B.indexof ('-') >= 0){ - -Sign = '-'; - +b = B.substr (1); - } + A if(A.indexof ('-') >= 0 && b.indexof ('-') >= 0){ at -A = A.SUBSTR (1); - -b = B.substr (1); - } - in if(Compare (A, B) < 0) {/*absolute a<b returns 0*/ - to return0; + } - theA = A.replace (/^0+/, "); * $b = B.replace (/^0+/, ");Panax Notoginseng - varDivisionsub =function(x, y) { the + varReturnres = [0]; A the varXlen =x.length; + - varYlen =y.length; $ $ for(vari=0;i<xlen-ylen;i++){ - - if(Compare (x, y + ' 0 ') >= 0){ the -Y + = "0";Wuyi theReturnres.push (0); - } Wu } - About while(Compare (x, y) >= 0){ $ -Returnres[0] + +; - -x =subtraction (x, y); A } + the return { - remainder:x, $Quotient:returnRes.join (' ') the } the } the the varDivisionres = ' 0 '; - in varDivisionsubres = { the remainder:a, theQuotient: ' 0 ' About } the the while(Compare (Divisionsubres.remainder,b) >= 0){ the +Divisionsubres =divisionsub (divisionsubres.remainder,b); - theDivisionres =addition (divisionres,divisionsubres.quotient);Bayi the } the - returnSign +Divisionres; -}
So that we have all the functions of the arithmetic of large integers, which can be encapsulated and become a simple arithmetic library of our own. Code details can be viewed Github:https://github.com/yux357/my-code-kata/blob/master/arithmetic.js
If you like my article, you can scan the QR code to follow my public number.
Try to share a little bit of my own development and practice experience every day ~
?
Code Kata: Large integer Arithmetic-in addition to JavaScript implementation