Here's our solution:
The base case is that the number fits in a single bit—that is, it has to be less than 2. If so, the number itself, 0 or 1, is the desired output.
In the recursive case, the rightmost bit of the result is the remainder of dividing the number by 2. That is, even numbers end with 0, and odd numbers end with 1. The rest of the result is a recursive call on the (integer) quotient of the number divided by 2. The combiner is join
because we want to string the digits together. It may be surprising that we don't use an arithmetic operator, since we're working with numbers, but the desired result is a numeral, which is a visible representation of a number, rather than the numeric value itself. A numeral is a text string, so the combiner is a string operation.
There's no reason to limit ourselves to decimal (base 10) and binary (base 2). How about base 7?
The base 7 digits are 0‒6, and the digit positions represent powers of 7.
base7
block above got the right answer.base7
block.base
block that takes the base as a second input:
base
block so that it can go up to base 36 by using the letters a
‒z
as digits with values 10‒35.
Another thing the AP people want you to know is that using a power of two as the base gives a shorthand for the binary representation — each digit represents a certain number of bits. Commonly used bases are octal (base 8), in which each digit represents three bits, and hexadecimal (base 16), in which each digit represents four bits.
from base
that takes a (text) string of digits and a base as inputs, and reports the corresponding number (which Snap! will show in decimal, of course, but you're converting to a number, not to a string of digits). Again, bases above ten are optional.