/* ============================================================================ * File: Fibonacci2.java * ---------------------------------------------------------------------------- * * This file is part of the Microsoft Supplemental UI Library for Visual J# .NET * Code Samples. * * Copyright (C) 2003 Microsoft Corporation. All rights reserved. * * THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, * WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. * ============================================================================ */ package RecursionDemo; /** * This class implements RecursiveFunction interface to demonstrate calculation of * Fibonacci numbers as recursive funtion. The code is optimized to recurse once only. * Refer Factorial.java also. */ public class Fibonacci2 implements RecursiveFunction { private RecursionStack stack; public String getName() { return "Fibonacci Function (optimized)"; } public String getDescription() { return "This function generates Fibonacci numbers." + " Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, ..." + " i.e. the next number is sum of previous two numbers." + " However instead of using double recursion it remembers one value" + " and uses only single recursion."; } public String getCode() { return "public int[] fibonacci2(int n) {\n" + " if (n <= 1)\n" + " return new int[] {0, 0};\n" + " else if (n == 2)\n" + " return new int[] {0, 1};\n" + " else {\n" + " int[] n1 = fibonacci2(n - 1);\n" + " return new int[] {n1[1], n1[0] + n1[1]};\n" + " }\n" + "}"; } public int doRecursion(int n) { return (fibonacci2(n))[0]; } public int[] fibonacci2(int n) { stack.push(n); int[] retVal; if (n <= 1) retVal = new int[] {0, 0}; else if (n == 2) retVal = new int[] {0, 0}; else { int[] n1 = fibonacci2(n - 1); retVal = new int[] {n1[1], n1[0] + n1[1]}; } stack.pop(retVal[1]); return retVal; } public void setRecursionStack(RecursionStack s) { stack = s; } }