int main() { int n = 10000; std::cout << "Trailing 0s of " << n << "! is " << trailingZeroes(n) << std::endl; assert(2499 == trailingZeroes(n)); return 0; }
TEST(FactorialTrailingZeroesTestCase, Normal) { EXPECT_EQ(1, trailingZeroes(5)); EXPECT_EQ(2, trailingZeroes(10)); EXPECT_EQ(6, trailingZeroes(25)); EXPECT_EQ(452137076, trailingZeroes(1808548329)); std::cout << "int " << sizeof(int) << std::endl; std::cout << "unsigned int " << sizeof(unsigned int) << std::endl; std::cout << "long " << sizeof(long) << std::endl; std::cout << "long long " << sizeof(long long) << std::endl; }
int trailingZeroes(int n) { return n>0 ? n/5+trailingZeroes(n/5) : 0; }
//recursive solution, code from oj leetcode discussion, a little faster than iterative solution int trailingZeroes2(int n) { return n == 0 ? 0 : n / 5 + trailingZeroes(n / 5); }
int main(int argc, char *argv[]) { printf("%d\n", trailingZeroes(atoi(argv[1]))); return(0); }
int trailingZeroes(int n) { return (n == 0)? 0: n / 5 + trailingZeroes(n/5); }
// all trailing 0 is from factors 5 * 2 // and number of factor 2 is more than number of factor 5 // calculate number of 5 and exponentials of 5 from 1 to n // use division rather than multyply can avoid overflow int trailingZeroes(int n) { return n < 5 ? 0 : n / 5 + trailingZeroes(n / 5); }