-
Notifications
You must be signed in to change notification settings - Fork 0
/
recursion.java
70 lines (53 loc) · 1.49 KB
/
recursion.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.util.Scanner;
public class recursion {
public static void main(String[] args) {
printnum(5);
int sum = 1;
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
calcsum(1, sum, i);
}
// ?? recursive function to print numbers from 1 to 5
public static void printnum(int n){
if ( n == 0) {
return;
}else{
System.out.println(n);
printnum(n-1);
}
}
// ?? Reursive function to calculate and print the sum of natural numbers upto the given number n ;
public static void calcsum(int n, int sum, int i) {
sum = sum + n;
if (n == i){
System.out.println(sum);
return;
}else{
calcsum(n+1, sum,i);
}
}
// ?? Recursive Function to calculate and print n factorial.
public static void calcfact(int n, int sum, int i) {
sum = sum * n;
if (n == i) {
System.out.println(sum);
return;
} else {
calcsum(n + 1, sum, i);
}
}
// ?? Recursive funtion to print x^n with stack height logn
public static int calcPower(int x , int n) {
if (n == 0){
return 1;
}
if (x==0) {
return 0;
}
if (n%2 == 0){
return calcPower(x, n/2) * calcPower(x, n/2);
}else{
return calcPower(x, n/2) * calcPower(x, n/2) * x ;
}
}
}