Skip to content

Instantly share code, notes, and snippets.

@elimelec
Created October 11, 2016 15:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elimelec/7e573bfee5076bd8e3f09e86ba749c9f to your computer and use it in GitHub Desktop.
Save elimelec/7e573bfee5076bd8e3f09e86ba749c9f to your computer and use it in GitHub Desktop.
public class Recursion {
public static void findHome(int from) {
if (from < 0) throw new IllegalArgumentException("from = " + from);
if (from == 0) { //home = 0
return;
}
findHome(from - 1);
}
public static int factorial(int n) {
if (n < 0) throw new IllegalArgumentException("n = " + n);
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}
public static int factorialLoop(int n) {
if (n < 0) throw new IllegalArgumentException("n = " + n);
int p = 1;
for (int i = 1; i <= n; i++) {
p = p * i;
}
return p;
}
public static void main(String[] args) {
int result;
findHome(10);
result = factorial(10);
result = factorialLoop(10);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment