forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFunctionRecursion.java
More file actions
49 lines (38 loc) · 946 Bytes
/
FunctionRecursion.java
File metadata and controls
49 lines (38 loc) · 946 Bytes
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
package com.examplehub.basics;
public class FunctionRecursion {
public static void main(String[] args) {
/*
* 1+2+3+...+10 = 55
*/
System.out.println("1+2+3+...+10 = " + sum(10));
/*
* 1+2+3+...100 = 5050
*/
System.out.println("1+2+3+...100 = " + sum(100));
/*
* 1*2*3*4*5 = 120
*/
System.out.println("1*2*3*4*5 = " + factorial(5));
/*
* 1*2*3*4*5*6 = 720
*/
System.out.println("1*2*3*4*5*6 = " + factorial(6));
/*
* pow(2, 3) = 8
*/
System.out.println("pow(2, 3) = " + power(2, 3));
/*
* pow(2, 10) = 1024
*/
System.out.println("pow(2, 10) = " + power(2, 10));
}
public static int sum(int n) {
return n == 0 ? 0 : n + sum(n - 1);
}
public static int factorial(int n) {
return n <= 1 ? 1 : n * factorial(n - 1);
}
public static int power(int n, int k) {
return k == 0 ? 1 : n * power(n, k - 1);
}
}