This post has been edited by **xclite**: 03 October 2012 - 07:01 AM

# Ruby Code Golf 3: Fibonacci Sequence

Page 1 of 1## 7 Replies - 13362 Views - Last Post: 16 May 2011 - 01:34 PM

### #1

# Ruby Code Golf 3: Fibonacci Sequence

Posted 09 May 2011 - 12:23 PM

This is a pretty straight forward problem: Create a method that returns the nth value of the Fibonacci sequence in as few characters as possible. Extra points for not repeating work (i.e. for not implementing the naive recursive solution)!

##
**Replies To:** Ruby Code Golf 3: Fibonacci Sequence

### #2

## Re: Ruby Code Golf 3: Fibonacci Sequence

Posted 09 May 2011 - 02:08 PM

Ok, this is me having never ever used Ruby before. Take this for what it's worth:

That assumes that i is positive, and f(0) = 0, and f(1) = 1. It's the recursive solution, but like I said, first time with Ruby.

def f(i) if(i==0||i==1) return i else return f(i-1)+f(i-2) end end

That assumes that i is positive, and f(0) = 0, and f(1) = 1. It's the recursive solution, but like I said, first time with Ruby.

### #3

## Re: Ruby Code Golf 3: Fibonacci Sequence

Posted 09 May 2011 - 03:25 PM

This assumes n is positive.

Spoiler

### #4

## Re: Ruby Code Golf 3: Fibonacci Sequence

Posted 09 May 2011 - 03:39 PM

Solving the linear recurrence gives me O(1) time.

Spoiler

### #5

## Re: Ruby Code Golf 3: Fibonacci Sequence

Posted 09 May 2011 - 03:53 PM

I guess the question is, which is more important? The efficiency or the pure character count?

### #6

## Re: Ruby Code Golf 3: Fibonacci Sequence

Posted 10 May 2011 - 02:32 AM

I never used ruby before. This is the shortest I could come up with (not using recursion):

def f(n) a,b=0,1 n.times{a,b=b,a+b} a end

This post has been edited by **Nallo**: 10 May 2011 - 02:43 AM

### #7

## Re: Ruby Code Golf 3: Fibonacci Sequence

Posted 10 May 2011 - 05:27 AM

Curtis Rutland, on 09 May 2011 - 06:53 PM, said:

I guess the question is, which is more important? The efficiency or the pure character count?

Playing with both is fine - I'd probably do two, one that emphasizes each. Also, I meant to uprep you but in my morning fail-mode I downrepped you so I'm finding two random posts to make up for it.

### #8

## Re: Ruby Code Golf 3: Fibonacci Sequence

Posted 16 May 2011 - 01:34 PM

Based on macosxnerd101's solution.

Spoiler

This post has been edited by **WaeV**: 16 May 2011 - 01:35 PM

Page 1 of 1