Code Kata: four operations of big integer -- javascript implementation of division method

Division can't be calculated by manual algorithm. Its basic idea is to do subtraction repeatedly to see how many divisors can be subtracted from the dividend, and the quotient is how much.

Division function:

  • If the former absolute value is less than the latter, it will return to zero directly
  • In subtraction, you don't need to subtract one by one. You can subtract based on the divisor * 10^n
 1 function division(a, b) { /*Enter two large numbers of string type*/
 2 
 3     a = a.toString();
 4 
 5     b = b.toString();
 6 
 7     var sign = '';
 8 
 9     if(a.indexOf('-') >= 0 && b.indexOf('-') < 0){
10 
11         sign = '-';
12 
13         a = a.substr(1);
14     }
15     else if(a.indexOf('-') < 0 && b.indexOf('-') >= 0){
16 
17         sign = '-';
18 
19         b = b.substr(1);
20     }
21 
22     if(a.indexOf('-') >= 0 && b.indexOf('-') >= 0){
23 
24         a = a.substr(1);
25 
26         b = b.substr(1);
27     }
28 
29     if(compare(a,b) < 0){   /*Absolute value a < B returns 0*/
30 
31         return 0;
32     }
33 
34     a = a.replace(/^0+/,'');
35 
36     b = b.replace(/^0+/,'');
37 
38     var divisionSub = function(x,y){
39 
40         var returnRes = [0];
41 
42         var xlen = x.length;
43 
44         var ylen = y.length;
45 
46         for(var i=0;i<xlen-ylen;i++){
47 
48             if(compare(x,y + '0') >= 0){
49 
50                 y += "0";
51 
52                 returnRes.push(0);
53             }
54         }
55 
56         while(compare(x,y) >= 0){
57 
58             returnRes[0] ++;
59 
60             x = subtraction(x,y);
61         }
62 
63         return {
64             remainder : x,
65             quotient : returnRes.join('')
66         }
67     }
68 
69     var divisionRes = '0';
70 
71     var divisionSubRes = {
72         remainder: a,
73         quotient: '0'
74     }
75 
76     while(compare(divisionSubRes.remainder,b) >= 0){
77 
78         divisionSubRes = divisionSub(divisionSubRes.remainder,b);
79 
80         divisionRes = addition(divisionRes,divisionSubRes.quotient);
81 
82     }
83 
84     return sign + divisionRes;
85 }
In this way, we have all the functions of the four operations of large integers, which can be encapsulated and become a simple four operations Library of our own.

For code details, see github: https://github.com/yux357/my-code-kata/blob/master/arithmetic.js



If you love my article, you can scan the two-dimensional code and pay attention to my WeChat official account.


Try to share my own development and practice experience every day ~

 

Tags: Javascript github less

Posted on Fri, 29 May 2020 12:14:22 -0400 by behrk2