Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 5e0e144

Browse files
committed
FEAT Implemented recursive method to compute factorials
1 parent f9dfe5f commit 5e0e144

File tree

1 file changed

+20
-8
lines changed

1 file changed

+20
-8
lines changed

‎src/PracticeAlgorithms.java

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ public static long FastFib(int N, HashMap<Integer, Long> cache) {
3434
}
3535
}
3636

37+
3738
public class PracticeAlgorithms {
3839
public static boolean isBetweenZeroAndOne(double x, double y) {
3940
return (0 < x && x < 1) && (0 < y && y < 1);
@@ -112,7 +113,7 @@ public static int[][] matrixTransposition(int[][] theMatrix) {
112113

113114

114115
/**
115-
* recursive method that returns the greatest integer not greater than log(N)
116+
* static recursive method that returns the greatest integer not greater than log(N)
116117
* to base two
117118
* */
118119
public static int lg(int N) {
@@ -121,6 +122,15 @@ public static int lg(int N) {
121122
return 1 + lg(N / 2);
122123
}
123124

125+
/**
126+
* static recursive method to compute the factorial of an integer "N"
127+
* */
128+
public static long fact(int N) {
129+
if (N == 1) return 1;
130+
131+
return N * fact(N - 1);
132+
}
133+
124134

125135
public static void main(String[] args) {
126136
Random generator = new Random();
@@ -165,17 +175,19 @@ public static void main(String[] args) {
165175

166176
// loop utilizing dynamic programming and memoization
167177
System.out.println("- Dynamic Programming and Memoization");
168-
for (int i = 0; i <= 80; i++) {
178+
for (int i = 0; i <= 40; i++) {
169179
System.out.println(Fibonacci.FastFib(i, cache));
170180
}
171181
System.out.println();
172182

173-
// loop utilizing the recursive fib method
174-
System.out.println("- Recursion");
175-
for (int i = 0; i <= 80; i++) {
176-
System.out.println(Fibonacci.Fib(i));
177-
}
178-
System.out.println();
183+
// loop utilizing the recursive fib method
184+
System.out.println("- Recursion");
185+
for (int i = 0; i <= 40; i++) {
186+
System.out.println(Fibonacci.Fib(i));
187+
}
188+
System.out.println();
179189

190+
System.out.printf("31!: %d\n", fact(31)); // N > 31 causes overflow
191+
System.out.println();
180192
}
181193
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /