forked from thuva4/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFactorialIterative.java
More file actions
29 lines (27 loc) · 1 KB
/
FactorialIterative.java
File metadata and controls
29 lines (27 loc) · 1 KB
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
import java.util.Scanner;
/*
Iterative function to find the factorial of a number
Time Complexity : O(N)
Space Complexity : O(1)
*/
public class FactorialIterative {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number whose factorial you want to find : ");
long n = in.nextLong();
if (n < 0) {
System.out.println("Factorial of a negative number is not defined");
} else {
long f = factorial(n);
System.out.println("Factorial of " + n + " is : " + f);
}
}
// Iterative function to find the factorial of a number
static long factorial(long n) {
long prod = 1L;
for (long i = 2; i <= n; i++) {
prod *= i;
}
return prod;
}
}