Để đếm số chữ số 0 ở cuối giai thừa của một số, mã Java như sau:
Ví dụ
import java.io.*; public class Demo{ static int trailing_zero(int num){ int count = 0; for (int i = 5; num / i >= 1; i *= 5){ count += num / i; } return count; } public static void main (String[] args){ int num = 1000000; System.out.println("The number of trailing zeroes in " + num +" factorial is " + trailing_zero(num)); } }
Kết quả
The number of trailing zeroes in 1000000 factorial is 249998
Lớp Demo chứa hàm trailing_zero khởi tạo count 0, lặp qua số cần tìm số 0 ở cuối giai thừa. Count trả về. Trong main, giá trị num định nghĩa, hàm gọi với tham số này. Thông báo hiển thị.