Spaces:
Running
Running
Create 7. Factorial
Browse files
Week 2: Methods, strings and lists/7. Factorial
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Example function calls:
|
| 2 |
+
public static void main(String[] args) {
|
| 3 |
+
System.out.println(factorial(3));
|
| 4 |
+
int f = factorial(4);
|
| 5 |
+
System.out.println(f);
|
| 6 |
+
}
|
| 7 |
+
|
| 8 |
+
Program outputs:
|
| 9 |
+
6
|
| 10 |
+
24
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
import java.util.Random;
|
| 19 |
+
|
| 20 |
+
public class Test{
|
| 21 |
+
public static void main(String[] args){
|
| 22 |
+
final Random r = new Random();
|
| 23 |
+
|
| 24 |
+
int[] p = {2,3,4,6,1};
|
| 25 |
+
for (int pa : p) {
|
| 26 |
+
System.out.println("Testing with parameter value " + pa);
|
| 27 |
+
System.out.println("Factorial: " + factorial(pa));
|
| 28 |
+
System.out.println("");
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
public static int factorial(int pa) {
|
| 35 |
+
int fact = 1;
|
| 36 |
+
|
| 37 |
+
for (int i=1; i<=pa; i++) {
|
| 38 |
+
fact *= i;
|
| 39 |
+
}
|
| 40 |
+
return fact;
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
Testing with parameter value 2
|
| 58 |
+
Factorial: 2
|
| 59 |
+
|
| 60 |
+
Testing with parameter value 3
|
| 61 |
+
Factorial: 6
|
| 62 |
+
|
| 63 |
+
Testing with parameter value 4
|
| 64 |
+
Factorial: 24
|
| 65 |
+
|
| 66 |
+
Testing with parameter value 6
|
| 67 |
+
Factorial: 720
|
| 68 |
+
|
| 69 |
+
Testing with parameter value 1
|
| 70 |
+
Factorial: 1
|
| 71 |
+
|
| 72 |
+
|