Count Good Numbers LeetCode solution in JavaScript

1
class Math1 {
2
// https://en.wikipedia.org/wiki/Modular_exponentiation
3
static modular_pow(base, exponent, modulus) {
4
if (modulus === 1n) return 0n;
5
let result = 1n;
6
base = base % modulus;
7
while (exponent > 0n) {
8
if (exponent % 2n == 1n) result = (result * base) % modulus;
9
exponent = exponent >> 1n;
10
base = (base * base) % modulus;
11
}
12
return result;
13
}
14
}
15

16
var countGoodNumbers = function (n) {
17
// NOTE: 0n, 1n, 2n, 3n, 4n, 5n are numbers in BigInt
18

19
n = BigInt(n); // convert to BigInt, to avoid no rounding issues
20

21
const odds = n / 2n,
22
evens = n - odds,
23
MOD = BigInt(Math.pow(10, 9) + 7);
24

25
// from wikipedia
26
return (
27
(Math1.modular_pow(4n, odds, MOD) * Math1.modular_pow(5n, evens, MOD)) % MOD
28
);
29
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0