Monday, May 27, 2013

Factorial in Java, Recursively and Non-Recursively

FactorialDemo demonstrates how to implement Factorial problem both recursively and non-recursively in Java.

1:  // Program by Luis Gallego Cardona.   

2:  package com.factorialdemo;
3:  import javax.swing.*;
4:  public class FactorialDemo {
5:       public static void main(String[] args) {
6:            String input; // hold the input
7:            int number; // hold a number
8:            // Get the number from the user
9:            input = JOptionPane.showInputDialog("Enter a non-negative number");
10:            number = Integer.parseInt(input);
11:            // Display the users input
12:            JOptionPane.showMessageDialog(null, number + "! is " + factorial(number) + ", using recursion"); // This shows the factorial using recursion
13:            JOptionPane.showMessageDialog(null, number + "! is " + nonrecursivefactorial(number) + ", not using recursion"); // This shows the factorial NOT using recursion
14:            System.exit(0);  
15:            // NOTE: What is the purpose of System.exit(0)? I know I have to call this whenever I use JOptionPane ... but that's about it.
16:       }
17:       private static int nonrecursivefactorial(int n) {
18:            int x; // this holds the number
19:            int fact = 1; // this is a place holder for the result of the factorial
20:            /** The for loops takes in a number as x, then assigns the value as n, which is the counter in the for loop.  
21:             * it then multiplies the number we passed in by 1 (base case), then it keeps multiplying the new number all the way until n is < 1. Thus breaks the loop
22:             */
23:            for (x = n; x > 1; x--)
24:                 fact *= x;
25:            return fact;
26:       }
27:       private static int factorial(int n) {
28:            if(n == 0)
29:                 return 1; // this is the base case , because 0! = 1
30:            else  
31:                 return n * factorial(n - 1);
32:       }
33:  }

No comments: