สมมติว่าเรามีจำนวน N ภารกิจของเราคือหา ln(N!) โดยใช้การเรียกตัวเอง (Recursion) ln() คือลอการิทึมฐาน e เพื่อแก้ปัญหานี้ เราสามารถใช้สูตรนี้ -
$$\ln(N!) = \ln(N \times (N-1) \times (N-2) \times \dots \times 2 \times 1) = \ln(N) + \ln(N-1) + \dots + \ln(1)$$
ตัวอย่างโค้ด
#include <iostream>
#include <cmath>
using namespace std;
double factLog(int n) {
if (n <= 1)
return 0;
return factLog(n - 1) + log(n);
}
int main() {
int N = 3;
cout << factLog(N);
}
ผลลัพธ์
1.79176