Last Updated: 5 Feb, 2021

Factorial of a Number

Easy
Asked in companies
HCL TechnologiesNagarro SoftwareCapegemini Consulting India Private Limited

Problem statement

Write a program to find the factorial of a number.

Factorial of n is:

n! = n * (n-1) * (n-2) * (n-3)....* 1

Output the factorial of 'n'. If it does not exist, output 'Error'.

Input format :
The only line of input contains a single integer.
Output format :
The only line of output prints the Factorial of the number or "Error" if it doesn't exist.
Constraints:
-10 <= n <= 12

Approaches

01 Approach

  • This can be done using an if-else-if ladder to check for negative,0, and positive numbers.
  • If the input is a positive number use a while loop to multiply n with n-1, n-2…1 and get the desired output.

02 Approach

  • This can be done using an if-else conditional statement to check for negative, and positive numbers.
  • If the input is a positive number use a for loop to multiply n with n-1, n-2…1 and get the desired output.