算法设计与应用基础系列16
来源:互联网 发布:lua c 数据传递 编辑:程序博客网 时间:2024/06/06 10:41
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Subscribe to see which companies asked this question.
The idea is:
- The ZERO comes from 10.
- The 10 comes from 2 x 5
- And we need to account for all the products of 5 and 2. likes 4×5 = 20 ...
- So, if we take all the numbers with 5 as a factor, we'll have way more than enough even numbers to pair with them to get factors of 10
Example One
How many multiples of 5 are between 1 and 23? There is 5, 10, 15, and 20, for four multiples of 5. Paired with 2's from the even factors, this makes for four factors of 10, so:23! has 4 zeros.
Example Two
How many multiples of 5 are there in the numbers from 1 to 100?
because 100 ÷ 5 = 20, so, there are twenty multiples of 5 between 1 and 100.
but wait, actually 25 is 5×5, so each multiple of 25 has an extra factor of 5, e.g. 25 × 4 = 100,which introduces extra of zero.
So, we need know how many multiples of 25 are between 1 and 100? Since 100 ÷ 25 = 4, there are four multiples of 25 between 1 and 100.
Finally, we get 20 + 4 = 24 trailing zeroes in 100!
The above example tell us, we need care about 5, 5×5, 5×5×5, 5×5×5×5 ....
Example Three
By given number 4617.
5^1 : 4617 ÷ 5 = 923.4, so we get 923 factors of 5
5^2 : 4617 ÷ 25 = 184.68, so we get 184 additional factors of 5
5^3 : 4617 ÷ 125 = 36.936, so we get 36 additional factors of 5
5^4 : 4617 ÷ 625 = 7.3872, so we get 7 additional factors of 5
5^5 : 4617 ÷ 3125 = 1.47744, so we get 1 more factor of 5
5^6 : 4617 ÷ 15625 = 0.295488, which is less than 1, so stop here.
Then 4617! has 923 + 184 + 36 + 7 + 1 = 1151 trailing zeroes.
To avoid the integer overflow as @localvar mentioned below(in case of 'n >=1808548329' ), the expression " i <= INT_MAX/5" is not a good way to prevent overflow, because 5^13 is > INT_MAX/5 and it's valid.
So, if you want to use "multiply", consider define the 'i' as 'long long' type.
int trailingZeroes(int n) {
int result = 0;
for(long long i=5; n/i>0; i*=5){
result += (n/i);
}
return result;
}
- 算法设计与应用基础系列16
- 算法设计与应用基础系列1
- 算法设计与应用基础系列2
- 算法设计与应用基础系列3
- 算法设计与应用基础系列4
- 算法设计与应用基础系列5
- 算法设计与应用基础系列6
- 算法设计与应用基础系列7
- 算法设计与应用基础系列8
- 算法设计与应用基础系列9
- 算法设计与应用基础系列10
- 算法设计与应用基础系列11
- 算法设计与应用基础系列12
- 算法设计与应用基础系列13
- 算法设计与应用基础系列14
- 算法设计与应用基础系列15
- 算法设计与应用基础系列17
- 算法设计与应用基础系列18
- leetcode617: Merge Two Binary Trees
- js的自定义属性及多一排图片的点击切换效果的实现
- hadoop 集群中所遇到的问题
- BlockingQueue详解
- c++ 纯虚函数/虚函数
- 算法设计与应用基础系列16
- LeetCode 535 Encode and Decode TinyURL (HashMap)
- c++11 新特性
- cups数据自动导入软件开发
- 二分查找变形记:从循环不变量说起
- BlockingQueue源码解析jdk1.8
- SylixOS启动读取配置文件
- 数据库 之 超键、候选键、主键、主属性、外键
- 指针数组及数组指针