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.

Was it helpful?

Solution

This is the algorithm you need to implement:

  1. Start the current count with 0;
  2. Multiply the current count by ten: this can be achieved by dupping 10 times, and then adding all dupes together;
  3. Read a digit;
  4. If it's null proceed to 8;
  5. Convert it to an actual number: this can be achieved by subtracting 48;
  6. Add it to the current count;
  7. Proceed to 2;
  8. Duplicate the current count;
  9. Adding the dupes together;
  10. Divide by ten using repeated subtraction; keep quotient and remainder;
  11. Grab the remainder;
  12. Make it a digit (add 48);
  13. Print it;
  14. Grab the quotient from 10;
  15. If it's not zero, goto 10;
  16. 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top