|
Exercise 1: Write a static method that computes 1*2*3*...*n = n! by using recursion. Here is a template for the exercise:
import java.io.*;
class Factorial {
public static void main(String[] args) {
// get integer value of n as a command line parameter
int n = (args.length==0)?20:Integer.parseInt(args[0]);
System.out.println(n+"!="+factorial(n));
return;
}
public static long factorial(int n) {
// code the body of this method
return 0L; // a stub
}
}
Factorials can be large number. The value of 100! is too big to be stored in a variable of type 'long', but it's not too large for the BigInteger class. Try modifying your factorial method so that it computes a return value of type BigInteger. [Read about the BigInteger class in the Java API first.] Use your code to compute 100!, which should end with 24 zeroes.
|
|
Exercise 2: Here's an exercise illustrating a situation where recursion
is not efficient: the computation of Fibonacci numbers. The Fibonacci sequence is a sequence of integers
whose first two elements are 0 and 1, and whose subsequent elements are found by adding the two
previous terms. That is, fn=fn-1+fn-2 for n > 1 with the
starting values f0=0 and f1=1.. This infinite sequence begins
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...
Implement a method FibonacciByRecursion(int n) that uses recursion to compute the n-th Fibonacci number.
A main routine that calls your method and a method that does the same computation iteratively are
provided below. You should detect a dramatic difference in the speeds of these two
computations.
import java.io.*;
public class Fibonacci {
public static void main (String argv[]) {
System.out.println("First 12 Fibonacci numbers computed using iteration:");
for (int i=0; i<12; i++) {
System.out.print(FibonacciByIteration(i)+", ");
}
System.out.println();
System.out.println("First 12 Fibonacci numbers computed using recursion:");
for (int i=0; i<12; i++) {
System.out.print(FibonacciByRecursion(i)+", ");
}
System.out.println();
System.out.println("The 39th Fibonacci number is "+FibonacciByIteration(39));
System.out.println("The 40th Fibonacci number is "+FibonacciByRecursion(40));
System.out.println("The 41st Fibonacci number is "+FibonacciByIteration(41));
System.out.println("The 42nd Fibonacci number is "+FibonacciByRecursion(42));
}
public static long FibonacciByIteration(int n) { // compute nth Fibonacci number using iteration
long fnMinus2=0;
long fnMinus1=1;
long fn=0;
if(n==0) {
fn=0;
}
else if (n==1) {
fn = 1;
}
else {
int i=1; // so far, we've only computed as far as f1
while (i < n) { // exit when i=n
// compute next term
fn = fnMinus1 + fnMinus2;
i++;
// update terms to add to get the next value in the sequence
fnMinus2 = fnMinus1;
fnMinus1 = fn;
}
}
return fn;
}
public static long FibonacciByRecursion(int n) { // compute nth Fibonacci number using recursion
return 0L; // a stub
}
}
|