Elliott Hughes | 2faa5f1 | 2012-01-30 14:42:07 -0800 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2011 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
Brian Carlstrom | 9f30b38 | 2011-08-28 22:41:38 -0700 | [diff] [blame] | 16 | |
| 17 | class Fibonacci { |
| 18 | |
| 19 | static int fibonacci(int n) { |
| 20 | if (n == 0) { |
| 21 | return 0; |
| 22 | } |
| 23 | int x = 1; |
| 24 | int y = 1; |
| 25 | for (int i = 3; i <= n; i++) { |
| 26 | int z = x + y; |
| 27 | x = y; |
| 28 | y = z; |
| 29 | } |
| 30 | return y; |
| 31 | } |
| 32 | |
| 33 | public static void main(String[] args) { |
Brian Carlstrom | a74ba83 | 2012-01-31 17:22:20 -0800 | [diff] [blame] | 34 | String arg = (args.length > 0) ? args[0] : "10"; |
Brian Carlstrom | 9f30b38 | 2011-08-28 22:41:38 -0700 | [diff] [blame] | 35 | try { |
Brian Carlstrom | a74ba83 | 2012-01-31 17:22:20 -0800 | [diff] [blame] | 36 | int x = Integer.parseInt(arg); |
| 37 | int y = fibonacci(x); /* to warm up cache */ |
| 38 | System.out.printf("fibonacci(%d)=%d\n", x, y); |
| 39 | y = fibonacci(x + 1); |
| 40 | System.out.printf("fibonacci(%d)=%d\n", x + 1, y); |
| 41 | } catch (NumberFormatException ex) { |
| 42 | System.err.println(ex); |
| 43 | System.exit(1); |
| 44 | } |
Brian Carlstrom | 9f30b38 | 2011-08-28 22:41:38 -0700 | [diff] [blame] | 45 | } |
| 46 | } |