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 24
Input: 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.
C++
#include <iostream>
using namespace std;
void printFactorialNums( int n)
{
int fact = 1;
int x = 2;
while (fact <= n) {
cout << fact << " " ;
fact = fact * x;
x++;
}
}
int main()
{
int n = 100;
printFactorialNums(n);
return 0;
}
|
Java
class GFG
{
static void printFactorialNums( int n)
{
int fact = 1 ;
int x = 2 ;
while (fact <= n)
{
System.out.print(fact + " " );
fact = fact * x;
x++;
}
}
public static void main (String[] args)
{
int n = 100 ;
printFactorialNums(n);
}
}
|
Python3
def printFactorialNums( n):
fact = 1
x = 2
while fact < = n:
print (fact, end = " " )
fact = fact * x
x + = 1
n = 100
printFactorialNums(n)
|
C#
using System;
class GFG
{
static void printFactorialNums( int n)
{
int fact = 1;
int x = 2;
while (fact <= n)
{
Console.Write(fact + " " );
fact = fact * x;
x++;
}
}
public static void Main ()
{
int n = 100;
printFactorialNums(n);
}
}
|
PHP
<?php
function printFactorialNums( $n )
{
$fact = 1;
$x = 2;
while ( $fact <= $n )
{
echo $fact , " " ;
$fact = $fact * $x ;
$x ++;
}
}
$n = 100;
echo printFactorialNums( $n );
?>
|
Javascript
<script>
function printFactorialNums(n)
{
let fact = 1;
let x = 2;
while (fact <= n) {
document.write(fact + " " );
fact = fact * x;
x++;
}
}
let n = 100;
printFactorialNums(n);
</script>
|
Time Complexity: O(x)
Auxiliary Space: O(1)
If there are multiple queries, then we can cache all previously computed factorial numbers to avoid re-computations.
This article is contributed by Shubham Sagar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
Please Login to comment...