Created
October 11, 2016 15:56
-
-
Save elimelec/7e573bfee5076bd8e3f09e86ba749c9f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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