0
$\begingroup$

I am not sure whether this is the right place to ask this question.

I would like to write a register machine code which when given an input of n in register 1, returns (also in register 1) the nth Fibonacci number. The Fibonacci numbers are 0 (the 0th), 1 (the 1st), 1 = 0 + 1 (the 2nd), etc.

I tried to write few lines of the codes, but unable to do the recursive property of Fibonacci sequence. Here is my code:

Let A, B, C be registers.

  1. (-A; 2,-)
  2. (+C; 1)
  3. (-C; 4,-)
  4. (+B; 5)
  5. (+A; 3)

I know that the fifth line is wrong but have no idea how to fix it. And I want to code to be as simple as possible (i.e. with fewest instructions). Thanks in advance.

$\endgroup$
  • 1
    $\begingroup$ I cant read your code. $\endgroup$ – A.Schulz May 13 '13 at 7:16
  • 5
    $\begingroup$ If you want us to write (or check) your program, at least give a hint on the programming language you are using. $\endgroup$ – vonbrand May 13 '13 at 11:50
  • 1
    $\begingroup$ +1 to @vonbrand Your language doesn't look standard to me ... And for your question I'm pretty sure that you will have to use conditional jump to do the recursive property. $\endgroup$ – wece May 13 '13 at 13:18
  • $\begingroup$ possible duplicate of How to write register machine code for Fibonacci $\endgroup$ – Hendrik Jan May 28 '13 at 21:58
1
$\begingroup$

Here is some code in C, which you can "compile" into your assembly language:

int x = 0, y = 1, z;
while (n--) {
  z = x;
  x = y;
  y += z;
}
return x;

After $n$ iterations of the loop, $x = F_n$ and $y = F_{n+1}$.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.