Last active
December 20, 2015 05:08
-
-
Save odhranroche/6075574 to your computer and use it in GitHub Desktop.
Recursive functions in Java to compare recursion with Lua
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
// Tested using Java version 1.7.0_21 in Eclipse Juno | |
// | |
// 3 recursive functions to compute the sum of the first n odd positive integers | |
// n can reach 4000 | |
public static int sumOdds1(int n, int sum, int counter){ // call : sumOdds1(20, 0, 0) | |
if (n == 0){ | |
return sum; | |
}else{ | |
if(counter % 2 == 1){ | |
sum = sum + counter; | |
return sumOdds1(--n, sum, ++counter); | |
}else{ | |
return sumOdds1(n, sum, ++counter); | |
} | |
} | |
} | |
// n can reach 9000 | |
public static int sumOdds2(int n, int sum, int counter){ // call : sumOdds2(20, 0, 1) | |
if (n == 0) | |
return sum; | |
else | |
return sumOdds2(n-1, sum+counter, counter+2); | |
} | |
// n can reach 15000 | |
public static int sumOdds3(int n){ | |
if (n==1) | |
return 1; | |
else | |
return (sumOdds3(n-1)) + (2*n - 1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment