Factorial of a number

PHOTO EMBED

Sun Feb 06 2022 02:48:25 GMT+0000 (Coordinated Universal Time)

Saved by @Uttam #java #mathematics #lecture #gfg #geeksforgeeks #factorial #iterative #recursive

// ITERATIVE CODE : Time Complexity : Θ(n), Auxiliary Space : Θ(1)

import java.io.*;
import java.util.*;

public class Main {

	static int fact(int n)
	{
		int res = 1;

		for(int i=2; i<=n; i++)
		{
			res = res * i;
		}
		return res;
	}

	public static void main (String[] args) {
		
		int number = 5;

		System.out.println(fact(number));

	}
}

// RECURSIVE CODE : Time Complexity : Θ(n), Auxiliary Space : Θ(n) 

import java.io.*;
import java.util.*;

public class Main {

	
	static int fact(int n)
	{
	    if(n==0)
	        return 1;
		
		return n * fact(n-1);
	}

	public static void main (String[] args) {
		
		int number = 5;

		System.out.println(fact(number));

	}
}
content_copyCOPY

Factorial Of Number Given a positive integer N. The task is to find factorial of N. Example 1: Input: N = 4 Output: 24 Explanation: 4! = 4 * 3 * 2 * 1 = 24 Example 2: Input: N = 13 Output: 6227020800 Explanation: 13! = 13 * 12 * .. * 1 = 6227020800 Your Task: You don't need to read input or print anything. Your task is to complete the function factorial() that takes N as parameter and returns factorial of N. Expected Time Complexity: O(N) Expected Auxilliary Space: O(1) Constraints: 0 <= N <= 18

https://practice.geeksforgeeks.org/tracks/DSASP-Mathematics/?batchId=190&tab=2