Find all factorial numbers less than or equal to n in C++

C++Server Side ProgrammingProgramming

Here we will see how to print all factorial numbers less than or equal to n, a number N is said to be factorial number if it is a factorial of a positive number. So some factorial numbers are 1, 2, 6, 24, 120.

To print factorial numbers, we do not need to find the factorial directly. Starting from i = 1, print factorial*i. Initially factorial is 1. Let us see the code for better understanding.

Example

 Live Demo

#include <iostream>
using namespace std;
void getFactorialNumbers(int n) {
   int fact = 1;
   int i = 2;
   while(fact <= n){
      cout << fact << " ";
      fact = fact * i;
      i++;
   }
}
int main() {
   int n = 150;
   getFactorialNumbers(n);
}

Output

1 2 6 24 120
raja
Published on 24-Oct-2019 13:08:48
Advertisements