Multiply a number by 2 in Brainfuck?
-
21-06-2021 - |
Question
Given an arbitrarily long number, how can I output its double? I know how to multiply small numbers together as long as the result is <10, but what about larger integers like 32984335, and doubling something like that? I don't know the right way to handle something like this.
Solution
This is the algorithm you need to implement:
- Start the current count with 0;
- Multiply the current count by ten: this can be achieved by dupping 10 times, and then adding all dupes together;
- Read a digit;
- If it's null proceed to 8;
- Convert it to an actual number: this can be achieved by subtracting 48;
- Add it to the current count;
- Proceed to 2;
- Duplicate the current count;
- Adding the dupes together;
- Divide by ten using repeated subtraction; keep quotient and remainder;
- Grab the remainder;
- Make it a digit (add 48);
- Print it;
- Grab the quotient from 10;
- If it's not zero, goto 10;
- The end.
All these steps consists of basic brainfuck idioms, so it should be easy to implement.
OTHER TIPS
Here's a start. It will multiply a byte of input, but I think you can build off it to make it work for any number. Basically, you take in a number, and store the number to multiply by (2) in the next pointer. You loop decrementing the first number, and then nest a loop decrementing the second number; in each iteration of the inner loop, you increment the pointer to the right of your second operand. This is your result.
, take input to ptr 0
[
- decrement first operand (input)
>++ number to multiply by (2) at ptr 1
[
>+ result in ptr 2
<- decrement second operand (2)
]
<
]
>> move to result
Here is my BF code: http://ideone.com/2Y9pk8
->>+>,+
[
-----------
[
-->++++++[-<------>]<
[->+<[->+<[->+<[->+<[>----<-<+>[->+<]]]]]]>
[-<++>]<+
>,+
[
-----------
[->+<]
]
>[-<+>]<
]
<[<]
>-[<++++++++[->++++++<]>.[-]]
>[<++++++++[->++++++<]>-.[-]>]
++++++++++.[-]
<+[-<+]
->>+>,+
]
It reads each number in each line until EOF, and multiply all numbers by two..
Here is the code for multiplying a number by 2.
,[>++<-]>.
Hope this helps.