# Count factorial numbers in a given range in C++

We are given the range starting from an integer value holded by a variable let’s say start till the variable end and the task is to count the total number of factorial numbers available in the given range.

## What is a factorial number

Factorial of a number is calculated by multiplying the digits in a number while decrementing thevalue of digit by 1. It is denoted by the symbol ‘!’ i.e. 0!, 1!, 2!, 3!, 5!,....,etc. Factorial of 0! and 1! is always 1.

I.e. factorial of 2 = 2 * (2-1) = 2 * 1 = 2
factorial of 3 = 3 * (3-1) * (2-1) = 3 * 2 * 1 = 6

## For Example

Input − start = 5, end = 600
Output − Count of factorial numbers are 3

Explanation − Since, there are 3 numbers available that have factorial numbers in the range 5-600.

Input − start = 1, end = 100
Output − Count of factorial numbers are 5

Explanation − Since, there are 5 numbers available that have factorial numbers in the range 5-600.

## Approach used in the below program is as follows

• Input the range and store in the variables start and end

• Take another variable, ‘fact’ to store the factorial values and initialise it with 1 and a temporary variable, ‘i’ to increase the numbers count.

• Start the loop, while fact is less than start and keep multiplying the fact with i to calculate the factorial and also, keep incrementing the value of i

• Start another loop, while fact is less than equals to end variable and keep incrementing the value of a variable r and keep setting fact to fact *i and keep incrementing value of i

• Now, return the value of r that is holding the total count of total number of factorial numbers

• Print the result.

## Example

Live Demo

#include <iostream>
using namespace std;
// To count the number of factorials
int factorials(int start, int end){
// Starting from 1 and find the first factorial number
// 'fact' greater than or equal to 'start'
int fact = 1, i = 1;
while (fact < start){
fact = fact*i;
i++;
}
// r to count factorial numbers in range start to end
int r = 0;
while (fact <= end){
r++;
fact = fact*i;
i++;
}
// Return the count of factorials in range
return r;
}
int main(){
int start = 5, end = 600;
cout << "Count of factorial numbers are " << factorials(start, end);
return 0;
}

## Output

If we run the above code it will generate the following output −

Count of factorial numbers are 3