给定一个代表数字N阶乘的数字K ,任务是找到N的值。
注意: K <10 18
例子:
Input: K = 120
Output: 5
Explanation:
5! = 1 * 2 * 3 * 4 * 5 = 120
Input: K = 6
Output: 3
Explanation:
3! = 1 * 2 * 3 = 6
方法:给出N的值!小于10 18 。通过观察我们可以看到,仅当N <= 18时,这才是正确的。因此,我们可以从1到18预先计算阶乘的值,并将其存储在哈希表或映射中。在预计算之后,对于N!的每个值,将在恒定时间内返回对应的N。
下面是上述方法的实现:
C++
// C++ program to find a number such that
// the factorial of that number is given
#include "bits/stdc++.h"
#define ll long long int
using namespace std;
// Map to precompute and store the
// factorials of the numbers
map m;
// Function to precompute factorial
int precompute()
{
ll fact = 1;
for (ll i = 1; i <= 18; i++) {
// Calculating the factorial for
// each i and storing in a map
fact = fact * i;
m[fact] = i;
}
}
// Driver code
int main()
{
// Precomputing the factorials
precompute();
int K = 120;
cout << m[K] << endl;
K = 6;
cout << m[K] << endl;
return 0;
}
Java
// Java program to find a number such that
// the factorial of that number is given
import java.util.*;
class GFG{
// Map to precompute and store the
// factorials of the numbers
static Map m = new HashMap();
// Function to precompute factorial
static void precompute()
{
int fact = 1;
for (int i = 1; i <= 18; i++) {
// Calculating the factorial for
// each i and storing in a map
fact = fact * i;
m.put(fact, i);
}
}
// Driver code
public static void main(String[] args)
{
// Precomputing the factorials
precompute();
int K = 120;
System.out.print(m.get(K) +"\n");
K = 6;
System.out.print(m.get(K) +"\n");
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 program to find a number such that
# the factorial of that number is given
# Map to precompute and store the
# factorials of the numbers
m = {};
# Function to precompute factorial
def precompute() :
fact = 1;
for i in range(1, 19) :
# Calculating the factorial for
# each i and storing in a map
fact = fact * i;
m[fact] = i;
# Driver code
if __name__ == "__main__" :
# Precomputing the factorials
precompute();
K = 120;
print(m[K]);
K = 6;
print(m[K]) ;
# This code is contributed by AnkitRai01
C#
// C# program to find a number such that
// the factorial of that number is given
using System;
using System.Collections.Generic;
class GFG{
// Map to precompute and store the
// factorials of the numbers
static Dictionary m = new Dictionary();
// Function to precompute factorial
static void precompute()
{
int fact = 1;
for (int i = 1; i <= 18; i++) {
// Calculating the factorial for
// each i and storing in a map
fact = fact * i;
m.Add(fact, i);
}
}
// Driver code
public static void Main(String[] args)
{
// Precomputing the factorials
precompute();
int K = 120;
Console.Write(m[K] +"\n");
K = 6;
Console.Write(m[K] +"\n");
}
}
// This code is contributed by 29AjayKumar
输出:
5
3