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 | |
Ian Rogers | 9ac995b | 2013-01-10 19:46:57 -0800 | [diff] [blame] | 17 | class Main { |
Brian Carlstrom | 9f30b38 | 2011-08-28 22:41:38 -0700 | [diff] [blame] | 18 | |
buzbee | 6969d50 | 2012-06-15 16:40:31 -0700 | [diff] [blame] | 19 | /* |
| 20 | // Iterative version |
Brian Carlstrom | 9f30b38 | 2011-08-28 22:41:38 -0700 | [diff] [blame] | 21 | static int fibonacci(int n) { |
| 22 | if (n == 0) { |
| 23 | return 0; |
| 24 | } |
| 25 | int x = 1; |
| 26 | int y = 1; |
| 27 | for (int i = 3; i <= n; i++) { |
| 28 | int z = x + y; |
| 29 | x = y; |
| 30 | y = z; |
| 31 | } |
| 32 | return y; |
| 33 | } |
buzbee | 6969d50 | 2012-06-15 16:40:31 -0700 | [diff] [blame] | 34 | */ |
| 35 | |
| 36 | // Recursive version |
| 37 | static int fibonacci(int n) { |
| 38 | if ((n == 0) || (n == 1)) { |
| 39 | return n; |
| 40 | } else { |
| 41 | return fibonacci(n - 1) + (fibonacci(n - 2)); |
| 42 | } |
| 43 | } |
Brian Carlstrom | 9f30b38 | 2011-08-28 22:41:38 -0700 | [diff] [blame] | 44 | |
| 45 | public static void main(String[] args) { |
Mathieu Chartier | 031768a | 2015-08-27 10:25:02 -0700 | [diff] [blame] | 46 | String arg = (args.length > 1) ? args[1] : "10"; |
Brian Carlstrom | 9f30b38 | 2011-08-28 22:41:38 -0700 | [diff] [blame] | 47 | try { |
Brian Carlstrom | a74ba83 | 2012-01-31 17:22:20 -0800 | [diff] [blame] | 48 | int x = Integer.parseInt(arg); |
buzbee | 6969d50 | 2012-06-15 16:40:31 -0700 | [diff] [blame] | 49 | int y = fibonacci(x); |
Brian Carlstrom | a74ba83 | 2012-01-31 17:22:20 -0800 | [diff] [blame] | 50 | System.out.printf("fibonacci(%d)=%d\n", x, y); |
| 51 | y = fibonacci(x + 1); |
| 52 | System.out.printf("fibonacci(%d)=%d\n", x + 1, y); |
| 53 | } catch (NumberFormatException ex) { |
Kevin Brodsky | f6c66c3 | 2015-12-17 14:13:00 +0000 | [diff] [blame] | 54 | System.out.println(ex); |
Brian Carlstrom | a74ba83 | 2012-01-31 17:22:20 -0800 | [diff] [blame] | 55 | System.exit(1); |
| 56 | } |
Brian Carlstrom | 9f30b38 | 2011-08-28 22:41:38 -0700 | [diff] [blame] | 57 | } |
| 58 | } |