Fibonacci Sequence

0

I'm doing selective process, and they are asking me to create a Fibonacci sequence, I just do not know how to create, until I tried (code below) but did not get results. I have to return the F (0) element of the Fibonacci sequence. could anyone help me?

Code:

class Fibonacci
 def element (n)
  expect (Fibonacci.new.element(0)).to eq 0
  return n if (1..0).include? n
  (element(n - 1) + element (n - 0))
 end
puts element (0)
end
    
asked by anonymous 15.10.2018 / 18:47

4 answers

0

Try this way.

Write the Fibonacci sequence in Ruby:

x, y = 0, 1
10.times do
  puts y
  x, y = y, x + y
end

In java:

class Fib {
  public static void main (String args[]) {
     int x = 0;
     int y = 1;
     int total = 1;
     for (int i=0; i<10; i++) {
       System.out.println(total);
       total = x+y;
       x = y;
       y = total;
     }
   }
}

Result in both cases: 1 1 2 3 5 8 13 21 34 55

    
15.10.2018 / 18:57
0

Try this way Lucas:

   def fibonacci( n )
      return  n  if ( 0..1 ).include? n
      ( fibonacci( n - 1 ) + fibonacci( n - 2 ) )
    end
    puts fibonacci( 10 )
    
15.10.2018 / 19:36
0

I like to reason, I hope it helps: 1 - we have 3 positions: predecessor, current and next;

2 - the ancestor r will always receive the current ;

3 - the current will always receive the next ;

4 - next will always receive current + predecessor .

logo:

predecessor = current

current = next

next = current + predecessor

I'm a beginner, but I hope I have helped. Good luck!

    
16.10.2018 / 12:44
0
def fib(n)
  return 1 if n < 2
  return fib(n - 1) + fib(n - 2)
end

I do not think it could be more concise.

In addition, you can find several other implementations here: link

    
18.10.2018 / 21:37