**27**

*Jul*

*2018*

### How to find Nth Number in a Factorial Series?

In mathematics, the factorial of a non-negative integer n, denoted by n! is the product of all positive integers less than or equal to n. For example,

The value of 0! is 1, according to the convention for an empty product.

The factorial operation is encountered in many areas of mathematics, notably in combinatorics, algebra, and mathematical analysis. Its most basic occurrence is the fact that there are n! ways to arrange n distinct objects into a sequence (i.e., permutations of the set of objects). This fact was known at least as early as the 12th century, to Indian scholars. Fabian Stedman, in 1677, described factorials as applied to change ringing.

Using Recursive Approach :

```
public class Factorial {
public static void main(String[] args) {
int n = 10;
long startTime = System.nanoTime();
System.out.println(Factorial(n));
long endTime = System.nanoTime();
long totalTime = endTime - startTime;
System.out.println("Total Time (nanoseconds) : " + (totalTime));
}
private static int Factorial(int n) {
if(n==0 || n==1)
return 1;
return Factorial(n-1)*n;
}
}
```

```
output:
3628800
Total Time (nanoseconds) : 263174
```

The time complexity of above algorithm is O(n) and space complexity is O(n)

Using Loop:

```
public class Factorial {
public static void main(String[] args) {
int n = 10;
long startTime = System.nanoTime();
System.out.println(Factorial(n));
long endTime = System.nanoTime();
long totalTime = endTime - startTime;
System.out.println("Total Time (nanoseconds) : " + (totalTime));
}
private static int Factorial(int n) {
int num = 1;
if(n == 0 || n == 1)
return 1;
for(int i=2;i<n+1;i++) {
num*=i;
}
return num;
}
}
```

```
output:
3628800
Total Time (nanoseconds) : 173310
```

The time complexity of the above algorithm is O(n) and space complexity is O(1)