blob: 9c943672a4c47c5c01945930c10f1007a655c774 [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
17class 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 Carlstroma74ba832012-01-31 17:22:20 -080034 String arg = (args.length > 0) ? args[0] : "10";
Brian Carlstrom9f30b382011-08-28 22:41:38 -070035 try {
Brian Carlstroma74ba832012-01-31 17:22:20 -080036 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 Carlstrom9f30b382011-08-28 22:41:38 -070045 }
46}