[英]Javascript: Implementing modulus where remainder 0 yields divisor instead
[英]Implementing Chinese Remainder Theorem in JavaScript
我一直在嘗試解決Advent of Code 2020 第 13 天第 2 部分任務。 我發現很多關於中國剩余定理的提示。 我在 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
為了與 bigint 一起工作,余數和模塊數組應對應於 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.