How to find Nth Number in a Factorial Series?
💻 coding

How to find Nth Number in a Factorial Series?

1 min read 275 words
1 min read
ShareWhatsAppPost on X
  • 1The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n.
  • 2The recursive approach to calculate factorial has a time complexity of O(n) and space complexity of O(n).
  • 3The iterative approach to calculate factorial has a time complexity of O(n) and space complexity of O(1).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

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

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)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 27 July 2018 · 1 min read · 275 words

Part of AskGif Blog · coding

You might also like

How to find Nth Number in a Factorial Series? | AskGif Blog