We have many challenges based on base 10, base 2, base 36, or even base -10, but what about all the other rational bases?
Task
Given an integer in base 10 and a rational base, return the integer in that base (as an array, string, etc.).
Process
It's difficult to imagine a rational base, so let's visualize it using Exploding Dots:
Consider this animation, expressing 17 in base 3:
Each dot represents a unit, and boxes represent digits: the rightmost box is the one's place, the middle box is the 3^1 place, and the leftmost box is the 3^2 place.
We can begin with 17 dots at the one's place. However, this is base 3, so the ones place has to be less than 3. Therefore, we "explode" 3 dots and create a dot on the box to the left. We repeat this until we end up with a stable position with no explodable dots (i.e. 3 dots in the same box).
So 17 in base 10 is 122 in base 3.
A fractional base is analogous to exploding some number of dots to more than one dots. Base 3/2 would be exploding 3 dots to create 2.
Expressing 17 in base 3/2:
So 17 in base 10 is 21012 in base 3/2.
Negative bases work similarly, but we must keep track of signs (using so-called anti-dots, equal to -1; represented by an open circle).
Expressing 17 in base -3:
Note, there are extra explosions to make the sign of all the boxes the same (ignoring zeros).
Thus, 17 in base 10 is 212 in base -3.
Negative rational bases work similarly, in a combination of the above two cases.
Rules
- No standard loopholes.
- The sign of each "digit" in the output must be the same (or zero).
- The absolute value of all digits must be less than the absolute value of the numerator of the base.
- You may assume that the absolute value of the base is greater than 1.
- You may assume that a rational base is in its lowest reduced form.
- You may take the numerator and the denominator of the base separately in the input.
- If a number has multiple representations, you may output any one of them. (e.g. 12 in base 10 can be
{-2, -8}
and{1, 9, 2}
in base -10)
Test cases:
Format: {in, base} -> result
{7, 4/3} -> {3, 3}
{-42, -2} -> {1, 0, 1, 0, 1, 0}
{-112, -7/3} -> {-6, -5, 0, -1, 0}
{1234, 9/2} -> {2, 3, 6, 4, 1}
{60043, -37/3} -> {-33, -14, -22, -8}
Since some inputs may have multiple representations, I recommend testing the output using this Mathematica snippet on TIO.
This is code-golf, so submissions with shortest byte counts in each language win!
For more information on exploding dots, visit the global math project website! They have a bunch of cool mathy stuff!