Skip to content

Commit a0e08d1

Browse files
author
Prashant Jain
committed
Added recursion
1 parent cefcb86 commit a0e08d1

2 files changed

Lines changed: 67 additions & 0 deletions

File tree

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package in.knowledgegate.dsa.recursion;
2+
3+
/**
4+
* Factorial
5+
* n! = n X (n-1) X ..... X 1
6+
* F(0) = 1
7+
* F(1) = 1
8+
* F(2) = 2
9+
* F(3) = 6 = 3 * 2
10+
* F(n) = n * F(n-1), n >= 1
11+
*/
12+
public class Factorial {
13+
public int fact(int n) {
14+
if (n == 0 || n == 1) return 1;
15+
return n * fact(n-1);
16+
}
17+
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package in.knowledgegate.dsa.recursion;
2+
3+
/**
4+
* The Fibonacci numbers, commonly denoted F(n)
5+
* form a sequence, called the Fibonacci sequence,
6+
* such that each number is the sum of the two
7+
* preceding ones, starting from 0 and 1. That is,
8+
*
9+
* F(0) = 0, F(1) = 1
10+
* F(n) = F(n - 1) + F(n - 2), for n > 1.
11+
* Given n, calculate F(n).
12+
*
13+
*
14+
* Example 1:
15+
* Input: n = 2
16+
* Output: 1
17+
* Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.
18+
*
19+
* Example 2:
20+
* Input: n = 3
21+
* Output: 2
22+
* Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.
23+
*
24+
* Example 3:
25+
* Input: n = 4
26+
* Output: 3
27+
* Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.
28+
*
29+
*
30+
* Constraints:
31+
* 0 <= n <= 30
32+
*/
33+
public class Fibonacci {
34+
public int fibRecursive(int n) {
35+
if (n == 0 || n == 1) return n;
36+
return fibRecursive(n - 1) +
37+
fibIterative( n - 2);
38+
}
39+
40+
public int fibIterative(int n) {
41+
if (n == 0 || n == 1) return n;
42+
int first = 0, second = 1;
43+
for (int i = 1; i < n; i++) {
44+
int next = first + second;
45+
first = second;
46+
second = next;
47+
}
48+
return second;
49+
}
50+
}

0 commit comments

Comments
 (0)