/**
   This class contains 3 recursive methods and 1 iterative one.
	One method finds the product of two integers.  The other three
	methods compute the nth value in a sequence.
	
	@author: Elizabeth Adams
	March 21, 2007
	Lab 18
	Sections 1,2, and 3
*/
public class RecursivePlay2
{

/**
   This method recursively computes the nth value in a sequence defined as follows:
	 S(1) = 2
	 S(n) = 2 * S(n-1) for n >= 2
	 
	 @param  the value desired
	 @return the nth value 
*/
public static int recursiveS ( int n)
{
   if (n < 1) // prevents infinite recursion (sequence not defined for negative nos)
	{
	  System.out.print (" can not compute a negative position in a sequence returning ");
	  return 0;
   }
   else if (n == 1)    // base case
	   return 2;
	else
	   return 2* recursiveS (n - 1); // recursive case
} // end recursiveS

/**
   This method iteratively computes the nth value in a sequence defined as follows:
	 S(1) = 2
	 S(n) = 2 * S(n-1) for n >= 2
	 
	 @param  the value desired
	 @return the nth value 
*/
public static int iterativeS (int n)
{
   int result;
	
	result = 2;    // initialization step
	for (int i = 1; i <= n - 1; i++)  // looping computation
	  result = result * 2;
	return result;
}  // end iterativeS
 
/**
   This method recursively computes the nth value in a sequence defined as follows:
	 T(1) = 1
	 T(n) = T(n-1) + 3 for n >= 2
	 
	 @param  the value desired
	 @return the nth value 
*/
public static int recursiveT  (int n)
{
  if (n < 1) // prevents infinite recursion (sequence not defined for negative #s)
	{
	  System.out.print (" can not compute a negative position in a sequence returning ");
	  return 0;
   }
   else if (n == 1)  // base case
	   return 1;
	else
	   return 3 + recursiveT (n - 1);  // recursive case
} // end recursiveT

/** 
  This method uses recursion to find the product of two numbers m and n
  It uses the following definition:
    m(1) = m
	 m(n) = m(n-1) + m for n >= 2

  @param  the multiplier
  @param  the multiplicand
  @return the product
*/
public static int recursiveMultiply (int m, int n)
{
    if (n < 0) //  n is not allowed to be negative or infinite recursion will occur
	 {
	    m = -m;
		 n = -n;
		 return recursiveMultiply(m,n);
	 }   
	 else if (n == 1)  // base case (note: since n is decreasing it is n that should be tested).
       return m;
	 else
	    return m + recursiveMultiply(m, n - 1); // recursive case
} // end recursiveMultiply


} // lend RecursivePlay2