Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.