0

I'd like to sum numbers that range from small (1) to very large (2**200). For that, I thought of using base-32 or base-36, such that the largest number would occupy a reasonable string (2**200 becomes bnklg118cog0000000000000000000000000000 in base-36).

However, how can I sum 2**200 with 1, for example? If I convert to decimal, it'll do 1.6069380442589901e+60 + 1 and the 1 will be ignored due to the precision. What I'd like is to do, for example: bnklg118cog0000000000000000000000000000 + 1 = bnklg118cog0000000000000000000000000001

I know I can convert a number to base 36 using .toString(36), but summing them would sum strings, not giving the correct result. Is it possible to do something like in hexadecimal, as (0xee + 0x11).toString(16) = "ff"?

Filipe
  • 532
  • 4
  • 16
  • 1
    Use [BigInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)? – robertklep Oct 15 '22 at 12:05
  • Hm, indeed if I do `BigInt(2**200)+BigInt(1)`, I get the correct number (in fact, I see now that the `bnklg118cog0000000000000000000000000000` was already cut due to precision. It's not what I wanted in the first place and it's more like a workaround (as I can't sum directly in base-36), but it'll do! Thanks! (If you send as a reply - maybe explaining a little -, I'll accept it.) – Filipe Oct 15 '22 at 12:13

1 Answers1

0

Using intermediate BigInt (suggested by @robertklep), I came up with this solution: (I use here a conversion function from here to avoid problems with very large numbers)

/* Convert `value` given in a basis `radix` to BigInt
* (from https://stackoverflow.com/a/55646905/3142385)
* @param   {string} value   Number written in a given in basis `radix`
* @param   {int}    radix   Basis of the number `value`
* @returns {BigInt}         Converted BigInt number
*/
function ConvertToBigInt(value, radix) {
  return [...value.toString()]
        .reduce((r, v) => r * BigInt(radix) + BigInt(parseInt(v, radix)), 0n);
}

/* Sum two values in base `radix` and return new value on the same basis
* @param   {string} value1   First value in base `radix` to be summed
* @param   {string} value2   Second value in base `radix` to be summed
* @param   {int}    radix   Basis of `value1` and `value2`
* @returns {string}         Summed values in base `radix`
*/
function Sum(value1,value2, radix) {
  return (ConvertToBigInt(value1.toString(),radix)+ConvertToBigInt(value2.toString(),radix)).toString(radix);
}

console.log(BigInt(2**200).toString(36),BigInt(2**199).toString(36),Sum("bnklg118comha6gqury14067gur54n8won6guf4","5tsaq0im6cb8n38dfdz0k033qfdkkbmgcbl8f7k",36))
// Output: "bnklg118comha6gqury14067gur54n8won6guf4" "5tsaq0im6cb8n38dfdz0k033qfdkkbmgcbl8f7k" "hhcw61juj0xpx9p4a5x1o09b7a4poyvd0yrp9mo"
Filipe
  • 532
  • 4
  • 16