![]() |
VOOZH | about |
A number N is called a factorial number if it is the factorial of a positive integer. For example, the first few factorial numbers are
1, 2, 6, 24, 120, ...
Given a number n, print all factorial numbers smaller than or equal to n.
Examples :
Input: n = 100
Output: 1 2 6 24Input: n = 1500
Output: 1 2 6 24 120 720
A simple solution is to generate all factorials one by one until the generated factorial is greater than n.
An efficient solution is to find next factorial using previous factorial.
1 2 6 24
Time Complexity: O(x)
Auxiliary Space: O(1)
Another solution : we can print factorial of a number such that factorial <=n by recursion.
1 2 6 24
Time Complexity: O(n)
Auxiliary Space: O(n)
If there are multiple queries, then we can cache all previously computed factorial numbers to avoid re-computations.