Skip to content

Commit 2155337

Browse files
author
SinghRahul
committed
New Algorithm to fins factorial in java.
1 parent 94f9cd1 commit 2155337

1 file changed

Lines changed: 27 additions & 31 deletions

File tree

Lines changed: 27 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,32 @@
11
public class Factorial {
2-
3-
private long recursiveFact(long n) {
4-
assert n > -1;
5-
if (n < 1) {
6-
return 1;
7-
}
8-
return n * recursiveFact(n - 1);
9-
}
10-
11-
private long loopFact(long n) {
12-
assert n > -1;
13-
long i = n;
14-
while (--i > 0) {
15-
n *= i;
16-
}
17-
return n;
18-
}
19-
20-
public void printRecursive(int n) {
21-
for (int i = 0; i < n; i++) {
22-
System.out.print(i + "! = ");
23-
System.out.println(recursiveFact(i));
24-
}
25-
2+
3+
public static void main(String[] args) {
4+
findFactorial();
265
}
27-
28-
public void printLoop(int n) {
29-
for (int i = 0; i < n; i++) {
30-
System.out.print(i + "! = ");
31-
System.out.println(loopFact(i));
6+
7+
public static void findFactorial() {
8+
9+
long a = 5; // The number whose factorial has to be calculated.
10+
long result = a;
11+
long c = 1;
12+
13+
if (a > 0) {
14+
while (c <= a - 1) {
15+
long b = (a - c);
16+
result *= b;
17+
c++;
18+
19+
}
20+
System.out.println("The factorial of " + a + " is " + result);
21+
} else {
22+
if (a == 0) {
23+
System.out.println("The factorial of 0 is 1");
24+
} else {
25+
System.out.println("The number is less than 0");
26+
}
27+
3228
}
33-
29+
3430
}
35-
31+
3632
}

0 commit comments

Comments
 (0)