Created
May 9, 2013 22:58
-
-
Save e0da/5551240 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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