给定数字N,任务是找到N阶乘的对数,即log(N!)。
注意: ln表示以e为底的对数。
例子:
Input: N = 2
Output: 0.693147
Input: N = 3
Output: 1.791759
方法:
方法-1:计算n!首先,取其日志值。
方法-2:使用log的属性,即取n,n-1,n-2…1的日志值之和。
ln(n!) = ln(n*n-1*n-2*…..*2*1) = ln(n)+ln(n-1)+……+ln(2)+ln(1)
下面是Method-2的实现:
C++
// C++ implementation of the above approach
#include
using namespace std;
// Function to calculate the value
double fact(int n)
{
if (n == 1)
return 0;
return fact(n - 1) + log(n);
}
// Driver code
int main()
{
int N = 3;
cout << fact(N) << "\n";
return 0;
}
C
// C implementation of the above approach
#include
#include
long double fact(int n)
{
if (n == 1)
return 0;
return fact(n - 1) + log(n);
}
// Driver code
int main()
{
int n = 3;
printf("%Lf", fact(n));
return 0;
}
Java
// Java implementation of the above approach
import java.util.*;
import java.io.*;
class logfact {
public static double fact(int n)
{
if (n == 1)
return 0;
return fact(n - 1) + Math.log(n);
}
public static void main(String[] args)
{
int N = 3;
System.out.println(fact(N));
}
}
Python
# Python implementation of the above approach
import math
def fact(n):
if (n == 1):
return 0
else:
return fact(n-1) + math.log(n)
N = 3
print(fact(N))
C#
// C# implementation of the above approach
using System;
class GFG
{
public static double fact(int n)
{
if (n == 1)
return 0;
return fact(n - 1) + Math.Log(n);
}
// Driver code
public static void Main()
{
int N = 3;
Console.WriteLine(fact(N));
}
}
// This code is contributed by ihritik
PHP
输出:
1.791759