สมมติว่าเรามีตัวเลข n เราต้องหาจำนวนศูนย์ต่อท้ายของ n!
ดังนั้นหากอินพุตเท่ากับ n =20 เอาต์พุตจะเป็น 4 เท่ากับ 20! =2432902008176640000
เพื่อแก้ปัญหานี้ เราจะทำตามขั้นตอนเหล่านี้
-
ชุดนับ :=0
-
สำหรับ i :=5, (n/i)> 1, update i :=i * 5, do
-
นับ :=นับ + (n /i)
-
-
จำนวนคืน
ให้เราดูการใช้งานต่อไปนี้เพื่อความเข้าใจที่ดีขึ้น
ตัวอย่าง
#include <iostream>
#include <cmath>
#define MAX 20
using namespace std;
int countTrailingZeros(int n) {
int count = 0;
for (int i = 5; n / i >= 1; i *= 5)
count += n / i;
return count;
}
main() {
int n = 20;
cout << "Number of trailing zeros: " << countTrailingZeros(n);
} อินพุต
20
ผลลัพธ์
Number of trailing zeros: 4