Last active
January 25, 2018 19:13
-
-
Save aire-con-gas/7e02f79bdfaed0d829432e586360f8e0 to your computer and use it in GitHub Desktop.
karatsuba
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const karatsuba = (x, y) => { | |
| const n = Math.max(x.toString().length, y.toString().length); | |
| if(n === 1) { | |
| return x * y; | |
| } | |
| let tenpowhalfn = Math.pow(10, parseInt(n / 2)); | |
| let tenpown = Math.pow(10, 2 * parseInt(n / 2)); | |
| let a = Math.floor(x / tenpowhalfn); | |
| let b = x % tenpowhalfn; | |
| let c = Math.floor(y / tenpowhalfn); | |
| let d = y % tenpowhalfn; | |
| return tenpown * karatsuba(a, c) + tenpowhalfn * (karatsuba(a, d) + karatsuba(b, c)) + karatsuba(b, d); | |
| }; | |
| function toFixed(x) { | |
| if (Math.abs(x) < 1.0) { | |
| var e = parseInt(x.toString().split('e-')[1]); | |
| if (e) { | |
| x *= Math.pow(10,e-1); | |
| x = '0.' + (new Array(e)).join('0') + x.toString().substring(2); | |
| } | |
| } else { | |
| var e = parseInt(x.toString().split('+')[1]); | |
| if (e > 20) { | |
| e -= 20; | |
| x /= Math.pow(10,e); | |
| x += (new Array(e+1)).join('0'); | |
| } | |
| } | |
| return x; | |
| } | |
| console.log('answer', toFixed(karatsuba(3141592653589793238462643383279502884197169399375105820974944592, 2718281828459045235360287471352662497757247093699959574966967627))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment