Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

นับจำนวนหลักของแฟกทอเรียลใน C++

เราได้รับจำนวนเต็ม งานคือการคำนวณแฟกทอเรียลแล้วนับจำนวนหลักของผลลัพธ์

แฟกทอเรียลคืออะไร?

n! = n × (n-1) × ... × 1 โดย 0! = 1! = 1

ตัวอย่าง

Input − factorial(6) Output − 3 digits

คำอธิบาย − 6! = 720 มี 3 หลัก

Input − factorial(12) Output − 9 digits

คำอธิบาย − 12! = 479001600 มี 9 หลัก

แนวทางการแก้ปัญหา (ใช้ Logarithm)

  • n < 0: คืนค่า 0 (ไม่มีแฟกทอเรียล)
  • n ≤ 1: คืนค่า 1
  • n > 1: ใช้สูตร log10(n!) = Σ log10(i) สำหรับ i=2 ถึง n
  • จำนวนหลัก = floor(log10(n!)) + 1
  • หลีกเลี่ยงการคำนวณแฟกทอเรียลจริงที่อาจ overflow

ตัวอย่างโค้ด C++

#include <iostream>
#include <cmath>
using namespace std;

int countDigitsInFactorial(int n) {
    if (n < 0) return 0;
    if (n <= 1) return 1;
    
    double digits = 0;
    for (int i = 2; i <= n; i++)
        digits += log10(i);
    
    return floor(digits) + 1;
}

int main() {
    cout << "1! digits: " << countDigitsInFactorial(1) << endl;
    cout << "6! digits: " << countDigitsInFactorial(6) << endl;
    cout << "106! digits: " << countDigitsInFactorial(106) << endl;
    return 0;
}

ผลลัพธ์

1! digits: 1
6! digits: 3
106! digits: 171

บทความนี้แสดงวิธีนับจำนวนหลักของแฟกทอเรียลโดยใช้ลอการิทึมฐาน 10 หลีกเลี่ยงการคำนวณแฟกทอเรียลจริงที่อาจล้นขนาดตัวแปร สูตร: digits = floor(Σ log10(i)) + 1