Skip to content

Instantly share code, notes, and snippets.

@iwestlin
Last active February 3, 2023 05:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iwestlin/4900abfb110455df0082e49b3a086671 to your computer and use it in GitHub Desktop.
Save iwestlin/4900abfb110455df0082e49b3a086671 to your computer and use it in GitHub Desktop.
葛立恒数的最后n位
// https://www.zhihu.com/question/372790433/answer/2873612363
// a 代表基数,m 代表被余数, t初始值表示m中0的个数(即因子5的个数)
function my_tetration_mod (a, t, m) {
if (m === 2n) return a % 2n
let phi_m // phi(m) 为欧拉函数,表示小于m且与m互质的自然数个数
if (t > 0) {
phi_m = m * 2n / 5n
} else {
phi_m = m / 2n
}
const pow = my_tetration_mod(a, t - 1, phi_m) + phi_m
return pow_mod(a, pow, m)
}
const digits = 100
console.log(my_tetration_mod(3n, digits, BigInt(`1${'0'.repeat(digits)}`))) // 9404248265018193851562535796399618993967905496638003222348723967018485186439059104575627262464195387n
// https://gist.github.com/krzkaczor/0bdba0ee9555659ae5fe
// console.log(pow_mod(3n, 587n, 1000n)) // 387
function pow_mod (base, pow, divisor) {
let result = 1n
let x = base % divisor
while (pow > 0n) {
if (pow % 2n === 1n) {
result *= x
result %= divisor
}
pow /= 2n
x *= x
x %= divisor
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment