0

I was working on a program and its job is to iterate through all possible ASCII characters. The code is able to successfully convert up to a point. When the number100000000000000008191 is entered the returned value is !__Ej2~nHK% when the next number 100000000000000008192 is entered the return value is !__Ej2~nHK%, the same value. This occurs for the next in the sequence and the next. It becomes so ineffective that 16384 numbers generate the same values.

This shouldn't happen as when counting in any number system different value numbers should not be the same.

Does anyone know what is wrong with it?

function generate(state) {
  const printables = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'
  var ones = state % printables.length
  var newstate = Math.floor(state / printables.length)
  if (newstate !== 0) {
    return generate(newstate) + printables[ones]
  } else {
    return printables[ones]
  }
}
console.log(generate(90071992514740992227))
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
Norvarg
  • 1
  • 4

1 Answers1

0

You're in excess of Number.MAX_SAFE_INTEGER, which is 9007199254740991. The extra value you're adding to this number is being lost as a round-off error, which is why your ASCII-converted value doesn't change.

kshetline
  • 12,547
  • 4
  • 37
  • 73
  • Is there any possibility of getting around it? – Norvarg Apr 19 '18 at 02:46
  • 1
    If you absolutely need to work with numbers this big, and accurately maintain so many digits of precision, you'll have to use a special library for extended precision numbers, like this, for example: https://github.com/peterolson/BigInteger.js – kshetline Apr 19 '18 at 02:48
  • Is it possible to store these numbers as strings and convert them to a base notation? – Norvarg Apr 19 '18 at 04:11
  • The BigInteger package does just that -- it handles large numbers as strings for input and output of values that can't be represented as native JavaScript numbers. But if you're asking if there's anything built into JavaScript to do base conversions on strings, then no, there isn't. You'd end up re-creating a lot of the work that goes into making a package like BigInteger if you're determined not to use someone else's package. – kshetline Apr 19 '18 at 05:03