math.js 1023 B

123456789101112131415161718192021222324252627282930313233
  1. // Array of number or bigint
  2. const max = (...values) => values.slice(1).reduce((x, y) => (x > y ? x : y), values.at(0));
  3. const min = (...values) => values.slice(1).reduce((x, y) => (x < y ? x : y), values.at(0));
  4. const sum = (...values) => values.slice(1).reduce((x, y) => x + y, values.at(0));
  5. // Computes modexp without BigInt overflow for large numbers
  6. function modExp(b, e, m) {
  7. let result = 1n;
  8. // If e is a power of two, modexp can be calculated as:
  9. // for (let result = b, i = 0; i < log2(e); i++) result = modexp(result, 2, m)
  10. //
  11. // Given any natural number can be written in terms of powers of 2 (i.e. binary)
  12. // then modexp can be calculated for any e, by multiplying b**i for all i where
  13. // binary(e)[i] is 1 (i.e. a power of two).
  14. for (let base = b % m; e > 0n; base = base ** 2n % m) {
  15. // Least significant bit is 1
  16. if (e % 2n == 1n) {
  17. result = (result * base) % m;
  18. }
  19. e /= 2n; // Binary pop
  20. }
  21. return result;
  22. }
  23. module.exports = {
  24. min,
  25. max,
  26. sum,
  27. modExp,
  28. };