Skip to content

Instantly share code, notes, and snippets.

@e0da
Created May 9, 2013 22:58
Show Gist options
  • Save e0da/5551240 to your computer and use it in GitHub Desktop.
Save e0da/5551240 to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
class Fib {
public static int plain(int index) {
if (index == 0) {
return 0;
} else if (index == 1) {
return 1;
} else {
return plain(index - 1) + plain(index - 2);
}
}
public static int cached(int index) {
ArrayList<Integer> values = new ArrayList<Integer>();
values.add(0);
values.add(1);
for (int i = 0; i <= index; i++) {
try {
values.get(i);
} catch (IndexOutOfBoundsException exception) {
values.add(values.get(i - 1) + values.get(i - 2));
}
}
return values.get(index);
}
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
System.out.println(Fib.plain(n));
System.out.println(Fib.cached(n));
}
}
#!/usr/bin/env ruby
class Fib
def self.plain(index)
case index
when 0; 0
when 1; 1
else plain(index-1) + plain(index-2)
end
end
def self.cached(index)
fibs = [0, 1]
(0..index).each do |i|
fibs[i] ||= fibs[i-1] + fibs[i-2]
end
fibs[index]
end
end
if __FILE__ == $0
unless ARGV.length == 1 && ARGV[0] =~ /\d+/
warn "Syntax: #{$0} N"
exit false
end
puts Fib.cached ARGV[0].to_i
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment