Write a program to find the factorial of a number.
Factorial Number: It is defined as the product of each number from 1 to n.
Example 1:
Input: num=5
Output: fact=5*4*3*2*1=120
Approach: Iterative
Java
public class Factorial {public static void main(String[] args) {int num = 5;int fact = factorial(num);System.out.println("Factorial of " + num + " is " + fact);}private static int factorial(int num) {int fact = 1;for (int i = num; i >= 1; i--) {fact = fact * i;}return fact;}}
C++
#include <bits/stdc++.h>using namespace std;//Function to find the factorail//of given numberint factorial(int n){int fact=1;//fact(n)=1*2*3...*n;for(int i=1;i<=n;i++)fact=fact*i;return fact;}int main(){int n=5;int fact=factorial(n);cout<<"Factorial is ";cout<<fact<<"\n";return 0;}//Time Complexity:O(n)//Space Complexity:O(1)
Approach: Recursive
Java
public class Factorial {public static void main(String[] args) {int num = 5;int fact = factorial(num);System.out.println("Factorial of " + num + " is " + fact);}private static int factorial(int num) {if (num == 1)return num;return num * factorialR(num - 1);}}
C++
#include <bits/stdc++.h>using namespace std;//Function to find the factorail//of given numberint factorial(int n){if(n==1)return n;//fact(n)=1*2*3...*n;return n*factorial(n-1);}int main(){int n=5;int fact=factorial(n);cout<<"Factorial is ";cout<<fact<<"\n";return 0;}
No comments:
Post a Comment