5

Getting this error TypeError: Cannot convert a BigInt value to a number:

function getCompositeNumbers() {
  let v = []
  let i = 1n

  while (i < 1000000n) {
    if (checkIfDivisible(i)) {
      v.push(i)
    }
    i++
  }

  return v
}

function checkIfDivisible(i) {
  if (i/2n == Math.floor(i/2n)) return true
  if (i/3n == Math.floor(i/3n)) return true
  if (i/5n == Math.floor(i/5n)) return true
  if (i/7n == Math.floor(i/7n)) return true
  if (i/11n == Math.floor(i/11n)) return true
  if (i/13n == Math.floor(i/13n)) return true
  return false
}
Lance
  • 75,200
  • 93
  • 289
  • 503

1 Answers1

9

BigInts are integers, they cannot represent fractional values - it makes no sense to round them. / is integer division, which implicitly truncates decimal digits.

To check for divisibility of BigInts, use

number / divisor * divisor == number
number % divisor == 0n
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • @PresidentJamesK.Polk Ah, brain fart. I even pondered about computing the remainder to compare it with zero but didn't think of just using the builtin operator for that… – Bergi Feb 14 '21 at 18:28