Prashant | Thu, 04 Jun, 2020 | 324
Finding factorial of a number is a really east task but when it comes to programming we have certain limitations like time limit and memory limit, so how do we solve it ?
We will be telling you 3 diffrent ways to do it
What is factorial?
Factorial is the product of an integer with it's all below integer till 1. In mathematic representation factorial represents by ! sign.
For Example:
Factorial 5 is:
5! = 120 [That is equivalent to 5*4*3*2*1 =120]
#include <stdio.h>
int main()
{
int num,i;
long int fact;
printf("Enter an integer number: ");
scanf("%d",&num);
/*product of numbers from num to 1*/
fact=1;
for(i=num; i>=1; i--)
fact=fact*i;
printf("\nFactorial of %d is = %ld",num,fact);
return 0;
}
Output
Enter an integer number: 7 Factorial of 7 is = 5040
#include <stdio.h>
/* function : factorial, to find factorial of a given number*/
long int factorial(int n)
{
int i;
long int fact=1;
if(n==1) return fact;
for(i=n;i>=1;i--)
fact= fact * i;
return fact;
}
int main()
{
int num;
printf("Enter an integer number :");
scanf("%d",&num);
printf("\nFactorial of %d is = %ld",num,factorial(num));
return 0;
}
Output
Enter an integer number: 7 Factorial of 7 is = 5040.
long int factorial(int n)
{
if(n==1) return 1;
return n*factorial(n-1);
}
Logic behind to implement these programs