/* ============================================================================ * File: Factorial.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 * factorial(n) as recursive funtion. */ public class Factorial implements RecursiveFunction { /** * Private variable to store the RecursionStack calling this recursive function. */ private RecursionStack stack; /** * Returns name of the recursive function */ public String getName() { return "Factorial Function"; } /** * Returns description of the recursive function */ public String getDescription() { return "This function generates n! (factorial of n)"; } /** * Returns executing code of the recursive function */ public String getCode() { return "public int factorial(int n) {\n" + " if (n <= 1)\n" + " return 1;\n" + " else\n" + " return (n * factorial(n - 1));\n" + "}"; } /** * Does recursion for 'n' steps. Returns computed value */ public int doRecursion(int n) { // push this call into the stack stack.push(n); int retVal; // value to return if (n <= 1) { // n <= 1, return 1 i.e. factorial(0) & factorial(1) is 1. retVal = 1; } else { // return n * factorial(n - 1); retVal = n * doRecursion(n - 1); } // pop this call out of the stack stack.pop(retVal); return retVal; } /** * Sets 'stack' as the RecursionStack for this recursive function */ public void setRecursionStack(RecursionStack s) { stack = s; } }