blob: 9c57ba76eba46aee345e193856bd221cbfdddec6 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
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 Carlstrom9f30b382011-08-28 22:41:38 -070016
Ian Rogers9ac995b2013-01-10 19:46:57 -080017class Main {
Brian Carlstrom9f30b382011-08-28 22:41:38 -070018
buzbee6969d502012-06-15 16:40:31 -070019/*
20 // Iterative version
Brian Carlstrom9f30b382011-08-28 22:41:38 -070021 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 }
buzbee6969d502012-06-15 16:40:31 -070034*/
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 Carlstrom9f30b382011-08-28 22:41:38 -070044
45 public static void main(String[] args) {
Mathieu Chartier031768a2015-08-27 10:25:02 -070046 String arg = (args.length > 1) ? args[1] : "10";
Brian Carlstrom9f30b382011-08-28 22:41:38 -070047 try {
Brian Carlstroma74ba832012-01-31 17:22:20 -080048 int x = Integer.parseInt(arg);
buzbee6969d502012-06-15 16:40:31 -070049 int y = fibonacci(x);
Brian Carlstroma74ba832012-01-31 17:22:20 -080050 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 Brodskyf6c66c32015-12-17 14:13:00 +000054 System.out.println(ex);
Brian Carlstroma74ba832012-01-31 17:22:20 -080055 System.exit(1);
56 }
Brian Carlstrom9f30b382011-08-28 22:41:38 -070057 }
58}