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

นับศูนย์ท้ายในแฟกทอเรียล (Trailing Zeros in Factorial) ในภาษา C/C++

จำนวนศูนย์ท้ายของ n! = จำนวนตัวประกอบ 5 ใน n! (เพราะ 2 มีมากกว่า)

Zeros = ⌊n/5⌋ + ⌊n/25⌋ + ⌊n/125⌋ + ...

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

#include <iostream>
using namespace std;

int trailingZeros(int n) {
    int count = 0;
    for (int i = 5; n/i >= 1; i *= 5)
        count += n / i;
    return count;
}

int main() {
    int n = 20;
    cout << "Trailing zeros in " << n << "! = " << trailingZeros(n);
    return 0;
}

ผลลัพธ์

Trailing zeros in 20! = 4