0 Replies - 1338 Views - Last Post: 14 October 2009 - 02:48 PM

#1 gbertoli3   User is offline

  • DIC at Heart + Code
  • member icon

Reputation: 41
  • View blog
  • Posts: 1,166
  • Joined: 23-June 08

Calculating Fibonacci with limit

Posted 14 October 2009 - 02:48 PM

Description: Use: array = Fibonacci(100) array.each do |i| puts i.to_s endCalculate the Fibonacci to 'x' number of places and return it as an array
# Calculate the Fibonacci to 'x' number of places and return it as an array
def Fibonacci(limit)
  # Creates a new array
  array = Array.new
  # Our first number
  num1 = 1
  # Our second number
  num2 = 1
  # Our next number
  nextNum = 0
  # Loop through until we reach our limit
  # NOTE: we need to subtract 2 because we will add two numbers to the beginning later
  while nextNum < (limit - 2)
    # Our third number will be made by adding our first and second number together
    num3 = num1 + num2;
    # Our new first number is our old second number
    num1 = num2;
    # Our new second number is our old third number
    num2 = num3;
    # Insert our new number into our array
    array.insert(nextNum, num3)
    # This will be our next number
    nextNum += 1 # You can also use: nextNum = nextNum.next
    # Exit the 'while' loop
  end
  # Insert the number 1 into the beginning of our array
  array.insert(0, 1)
  # Insert the number 1 into the 2nd position of our array
  array.insert(1, 1)
  # Return our array
  return array
  # Exit the method
end


Is This A Good Question/Topic? 0
  • +

Page 1 of 1