📜  查找所有小于或等于n的阶乘数

📅  最后修改于: 2021-05-04 10:22:29             🧑  作者: Mango

如果数字N是正整数的阶乘,则称为阶乘数。例如,前几个阶乘数是
1,2,6,24,120,…
给定数字n,请打印所有小于或等于n的阶乘数。
例子 :

Input : n = 100
Output : 1 2 6 24

Input : n = 1500
Output : 1 2 6 24 120 720

一个简单的解决方案是逐个生成所有阶乘,直到生成的阶乘大于n为止。
一个有效的解决方案是使用先前的阶乘查找下一个阶乘。

C++
// CPP program to find all factorial numbers
// smaller than or equal to n.
#include 
using namespace std;
 
void printFactorialNums(int n)
{
    int fact = 1;
    int x = 2;
    while (fact <= n) {
        cout << fact << " ";
 
        // Compute next factorial
        // using previous
        fact = fact * x;
 
        x++;
    }
}
 
// Driver code
int main()
{
    int n = 100;
    printFactorialNums(n);
    return 0;
}


Java
// Java program to find all factorial numbers
// smaller than or equal to n.
 
class GFG
{
    static void printFactorialNums(int n)
    {
        int fact = 1;
        int x = 2;
        while (fact <= n)
        {
            System.out.print(fact + " ");
     
            // Compute next factorial
            // using previous
            fact = fact * x;
     
            x++;
        }
    }
     
    // Driver code
    public static void main (String[] args)
    {
        int n = 100;
        printFactorialNums(n);
    }
}
 
// This code is contributed by Anant Agarwal.


Python3
# Python3 program to find all factorial
# numbers smaller than or equal to n.
 
def printFactorialNums( n):
    fact = 1
    x = 2
    while fact <= n:
        print(fact, end = " ")
         
        # Compute next factorial
        # using previous
        fact = fact * x
         
        x += 1
 
# Driver code
n = 100
printFactorialNums(n)
 
# This code is contributed by "Abhishek Sharma 44"


C#
// C# program to find all factorial numbers
// smaller than or equal to n.
using System;
 
class GFG
{
    static void printFactorialNums(int n)
    {
        int fact = 1;
        int x = 2;
        while (fact <= n)
        {
            Console.Write(fact + " ");
     
            // Compute next factorial
            // using previous
            fact = fact * x;
     
            x++;
        }
    }
     
    // Driver code
    public static void Main ()
    {
        int n = 100;
        printFactorialNums(n);
    }
}
 
// This code is contributed by vt_m.


PHP


Javascript


输出:

1 2 6 24