Modulo in JavaScript - large number

前端 未结 6 1861
情深已故
情深已故 2021-01-07 20:39

I try to calculate with JS\' modulo function, but don\'t get the right result (which should be 1). Here is a hardcoded piece of code.

var checkSum = 21050170         


        
6条回答
  •  广开言路
    2021-01-07 21:26

    For those who simply want to copy&paste a working (functional) solution in ES6 to check IBANs:

    function isIBAN(s){
        const rearranged = s.substring(4,s.length) + s.substring(0,4);
        const numeric   = Array.from(rearranged).map(c =>(isNaN(parseInt(c)) ? (c.charCodeAt(0)-55).toString() : c)).join('');
        const remainder = Array.from(numeric).map(c => parseInt(c)).reduce((remainder, value) => (remainder * 10 + value) % 97,0);
    
        return  remainder === 1;}
    

    You could even write it as a one-liner.

    The modulo operation is performed on the array of integers storing the actual number (divident, applied as string to function):

    function modulo(divident, divisor){
       return Array.from(divident).map(c => parseInt(c)).reduce((remainder, value) => (remainder * 10 + value) % divisor,0);
    };
    

    This works because Modulo is distributive over addition, substraction and multiplication:

    • (a+b)%m = ((a%m)+(b%m))%m
    • (a-b)%m = ((a%m)-(b%m))%m
    • (ab)%m = ((a%m)(b%m))%m

    The IBAN function transpiled to ES5 looks like:

    function (s) {
        var rearranged = s.substring(4, s.length) + s.substring(0, 4);
        var numeric = Array.from(rearranged).map(function (c) { return (isNaN(parseInt(c)) ? (c.charCodeAt(0) - 55).toString() : c); }).join('');
        var remainder = Array.from(numeric).map(function (c) { return parseInt(c); }).reduce(function (remainder, value) { return (remainder * 10 + value) % 97; }, 0);
        return remainder === 1;
    };
    

提交回复
热议问题