Skip to content

Instantly share code, notes, and snippets.

@mmowbray
Last active August 29, 2015 14:00
Show Gist options
  • Save mmowbray/11390790 to your computer and use it in GitHub Desktop.
Save mmowbray/11390790 to your computer and use it in GitHub Desktop.
249 Winter 2014 Recursion
// --------------------------------------------------------------------------------------------------------
// Recursion249.java
// Written by: Maxwell Mowbray
// For COMP 249 Section PP - Tutorial PB - Winter 2014.
// These are the questions from the COMP 249 final which dealt with recursion
// --------------------------------------------------------------------------------------------------------
public class Recursion249
{
public static int count = 0;
public static void main(String[] args)
{
//magic(6);
//System.out.println(count);
System.out.println(exp(3,10));
}
// Question 1: Analyse this recursive method and predict its output when main() has only:
/*public static void main(String[] args)
{
magic(6);
System.out.println(count);
}*/
public static int magic(int n)
{
count++;
int ret = 0;
if (n < 3)
ret = n;
else
ret = magic(n-2) + n + magic(n-3);
System.out.println(ret);
return ret;
}
/*
Question 2: e^x can be approximated with a Taylor series.
e^x = 1 + x/1! + x^2/2! + x^3/3! + ... + x^n/n!
where x is any integer and n is a sufficiently large integer (larger integer -> closer approximation of e^x)
In simple terms, you can calculate e^7 by computing 1 + 7/1! + 7^2/2! + 7^3/3! + ...
First, write two recursive functions that will help. The first is the factorial function (factorial(n)) that
recursively computes n!. Then, a recursive function that computes x^n. This function is pow (x,n).
*/
public static double factorial(int n) //go to a maximum of ten for n for an int or the number will be too large for an int
{
if (n == 0)
return 1;
else
return (n * factorial(n-1));
}
public static double pow (int x, int n) //x^4 = x * x^3. x^3 = x * x^2. and so on...
{
if (n == 0)
return 1;
else
return (x * pow(x, n - 1));
}
//To get the series computer, put both functions together recursively
public static double exp (int x, int n)
{
if (n == 0)
return 1;
else
return ((pow(x,n)) / factorial(n) + exp(x, n - 1));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment