Brian Carlstrom | 9f30b38 | 2011-08-28 22:41:38 -0700 | [diff] [blame] | 1 | // Copyright 2011 Google Inc. All Rights Reserved. |
| 2 | |
| 3 | class Fibonacci { |
| 4 | |
| 5 | static int fibonacci(int n) { |
| 6 | if (n == 0) { |
| 7 | return 0; |
| 8 | } |
| 9 | int x = 1; |
| 10 | int y = 1; |
| 11 | for (int i = 3; i <= n; i++) { |
| 12 | int z = x + y; |
| 13 | x = y; |
| 14 | y = z; |
| 15 | } |
| 16 | return y; |
| 17 | } |
| 18 | |
| 19 | public static void main(String[] args) { |
| 20 | try { |
| 21 | if (args.length == 1) { |
| 22 | int x = Integer.parseInt(args[0]); |
| 23 | int y = fibonacci(x); /* to warm up cache */ |
| 24 | System.out.printf("fibonacci(%d)=%d\n", x, y); |
Brian Carlstrom | c228252 | 2011-09-17 10:33:14 -0700 | [diff] [blame] | 25 | y = fibonacci(x + 1); |
| 26 | System.out.printf("fibonacci(%d)=%d\n", x + 1, y); |
Brian Carlstrom | 9f30b38 | 2011-08-28 22:41:38 -0700 | [diff] [blame] | 27 | } |
| 28 | } catch (NumberFormatException ex) {} |
| 29 | } |
| 30 | } |