javascript - 在 JavaScript 中实现中国剩余定理

标签 javascript typescript algorithm crt

我一直在尝试解决Advent of Code 2020 day 13第 2 部分任务。我发现了很多关于 Chinese Remainder Theorem 的提示。 .我在 npm 的 nodejs-chinesse-remainders 之后尝试了一些实现。但是这个实现似乎很旧(2014),并且还需要针对 Big Int 案例的额外库。
我怎样才能实现模乘逆?如何重构我提供链接的 npm 模块中定义的 CRT 算法?

最佳答案

作为一种自我回应,目的是制作一个 wiki,为那些将来需要在 javascript/typescript 中实现 CRT 的人找到这个解决方案:
首先想到的是执行Modular Multiplicative Inverse ,对于这个任务,我们试图找到一个 x 使得:a*x % modulus = 1

const modularMultiplicativeInverse = (a: bigint, modulus: bigint) => {
  // Calculate current value of a mod modulus
  const b = BigInt(a % modulus);
    
    // We brute force the search for the smaller hipothesis, as we know that the number must exist between the current given modulus and 1
    for (let hipothesis = 1n; hipothesis <= modulus; hipothesis++) {
        if ((b * hipothesis) % modulus == 1n) return hipothesis;
    }
      // If we do not find it, we return 1
    return 1n;
}
然后按照您提供的文章和示例代码:
const solveCRT = (remainders: bigint[], modules: bigint[]) => {
    // Multiply all the modulus
    const prod : bigint = modules.reduce((acc: bigint, val) => acc * val, 1n);
    
    return modules.reduce((sum, mod, index) => {
        // Find the modular multiplicative inverse and calculate the sum
    // SUM( remainder * productOfAllModulus/modulus * MMI ) (mod productOfAllModulus) 
        const p = prod / mod;
        return sum + (remainders[index] * modularMultiplicativeInverse(p, mod) * p);
    }, 0n) % prod;
}
这样你就可以使用 ES6 函数,例如 reduce为了与 bigints 一起工作,余数和模块数组应对应于 ES2020 的 BigInt
例如:
  x mod 5 = 1
  x mod 59 = 13
  x mod 24 = 7
// Declare the problem and execute function
// You can not parse them to BigInt here, but TypeScript will complain of operations between int and bigint
const remainders : bigint[] = [1, 13, 7].map(BigInt)
const modules: bigint[] = [5, 59, 24].map(BigInt)

solveCRT(remainders, modules) // 6031

关于javascript - 在 JavaScript 中实现中国剩余定理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65275951/

相关文章:

C语言 : Why my code get infinite loop and how to use recursion to solve Merge Sort problem?

javascript - 按钮 href 不工作

javascript - Angular4中具有功能的属性指令

c# - 是否选中了两个或三个单选按钮中的任何一个

子类中的 Typescript 方法重载

javascript - Angular ReactiveForms FormArray removeAt 移除FormArray中的所有元素

http - 当 header 为 { 'Authorization' : 'Bearer ' + token } 时,req.body 为空

用于字符串相似性的 Python 摘要/哈希

sql - 重新排序 SQL Server 数据库中的项目

javascript - 如何在普通项目中安装 Node 的文件系统