Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Đếm chữ số của giai thừa trong C++

Cho một số nguyên, nhiệm vụ là tính giai thừa rồi đếm số chữ số của kết quả.

Giai thừa (Factorial)

n! = n × (n-1) × ... × 1. 0! = 1! = 1.

Ví dụ: 2! = 2, 3! = 6, 6! = 720 (3 chữ số), 12! = 479001600 (9 chữ số).

Phương pháp tối ưu (Logarit)

Thay vì tính trực tiếp (dễ tràn số), dùng công thức: số chữ số = floor(log₁₀(n!)) + 1 = floor(Σ log₁₀(i)) + 1 với i=2..n

Ví dụ

Input - factorial(6) Output - 3
Input - factorial(12) Output - 9

Ví dụ code C++

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

int count_digits(int num) {
    if (num < 0) return 0;
    if (num <= 1) return 1;

    double d = 0;
    for (int i = 2; i <= num; i++)
        d += log10(i);
    return floor(d) + 1;
}

int main() {
    cout << "number of digits in factorial(1) is: " << count_digits(1) << endl;
    cout << "number of digits in factorial(6) is: " << count_digits(6) << endl;
    cout << "number of digits in factorial(106) is: " << count_digits(106) << endl;
    return 0;
}

Kết quả

number of digits in factorial(1) is: 1
number of digits in factorial(6) is: 3
number of digits in factorial(106) is: 171