Search

vendredi 17 février 2017

Fibonacci numbers

Context

Fibonacci sequence F is defined by :

  • F(1) = F(2) = 1
  • F(n+2) = F(n+1) + F(n) for any n > 1
Hence, the sequence is 1, 1, 2, 3, 5, 8, ...

Let's display all Fibonacci numbers up to the Nth one, N given by user, using a comma-separated display

Initial state

  • Memory: empty
  • Cursor: first cell
  • Input: a number N > 1

Process

  • First, let's store the comma code, to display it more quickly
  • Then, read the number N
  • Initialize the sequence with values 1 and 1
  • Display "1,1" as the first sequence values
  • Decrease counter N by 2 (because first 2 values are already displayed)
  • While counter is not null
    • Decrease counter
    • Copy the second value of the sequence
    • Compute the sum of the 2 current sequence values
    • Store the second's copy as first, and sum as new second
    • Print comma
    • Copy / print newly computed sum

Code - try it

store comma
>++++[-<+++++++++++>]

read number
>,[>++++++[-<-------->]>+++++++++[-<<<[->+>+<<]>>[-<<+>>]>]<<[-<+>],]

print first numbers (1)
<<+++++.-----.+++++.-----

initialize sequence
>-->+>+

start loop
<<
[-
  move / copy second
  >>[->+>+<<]
  sum first / second
  <[->>>+<<<]
  move second to first place
  >>[-<<+>>]
  move / copy sum
  >[-<<+>>>+<]
  print comma
  <<<<<.
  print number
  >>>>>>[>>>>++++++++++<<<<[->+>>+>-[<-]<[->>+<<<<[->>>+<<<]>]<<]>+[-<+>]>>>[-]>[-<<<<+>>>>]<<<<]<[>++++++[<++++++++>-]<-.[-]<]<<<<
]

Final state

  • Memory: 44 0 F(N-1) F(N)
  • Cursor: second cell
  • Input: empty
  • Output: all Fibonacci numbers up to F(N), comma-separated


Aucun commentaire:

Enregistrer un commentaire