I chose the same kind of method... recursion is too slow.
def fibonacci(count=0, x=0, y=1)
# This method satifies the spec for generating a list for a given number of
# iterations, or to iterate to infinity
case count
when 0
# They want to go on forever!
while true do
x, y = y, x+y
print "#{x}, "
end
else
count.times do
x, y = y, x+y
print "#{x}, "
end
puts
end
end
I don't like the fact that it puts a comma even on the last iteration.
If you don't pass a count it'll just go on forever.
Then a module to mixin to Fixnum and Bignum:
module Fibonacci
# This will mixin to Fixnum and Bignum so that you can easily generate an
# array of fib numbers
def fib (x=0, y=1)
fibs=[x]
(self-1).times do
x, y = y, x+y
fibs << x
end
fibs
end
def is_fibonacci?
# Only need to check fib numbers that are fixnums
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987,
1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393,
196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887,
9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141,
267914296, 433494437, 701408733].include?(self) if self.class == Fixnum
# Noted that the wait for 300 iterations is noticable so decided to
# draw the line there. I was unable to come up with a reliable and fast
# way to know how many times to iterate based on the number being
# checked.
# If you want to know if a number larger than max_check+1 is a fibonacci
# number then you're out of luck with this method!
if self.class == Bignum
max_check =
137347080577163115432025771710279131845700275212767467264610200
case
when self == 1134903170
true
when self <= max_check
300.fib.include?(self)
when self == max_check+1
# max_check+1 IS a known fibonacci number
true
else
raise "argument out of range"
end
end
end
end
On Fri, Oct 31, 2008 at 12:48 PM, Paul Robinson <[EMAIL PROTECTED]> wrote:
>
> So the deadline has passed. Has anybody got any code they wish to share?
snip
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"NWRUG" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/nwrug-members?hl=en
-~----------~----~----~----~------~----~------~--~---