Factorial Trailing Zeroes
Given an integer?n, return the number of trailing zeroes in?n!.
Note:?Your solution should be in logarithmic time complexity.
給定一個整數(shù)n,返回n!(n的階乘)數(shù)字中的后綴0的個數(shù)。
考慮n!的質(zhì)數(shù)因子。后綴0總是由質(zhì)因子2和質(zhì)因子5相乘得來的。如果我們可以計數(shù)2和5的個數(shù),問題就解決了。考慮下面的例子:
n = 5: 5!的質(zhì)因子中?(2 * 2 * 2 * 3 * 5)包含一個5和三個2。因而后綴0的個數(shù)是1。
n = 11: 11!的質(zhì)因子中(2^8 * 3^4 * 5^2 * 7)包含兩個5和三個2。于是后綴0的個數(shù)就是2。
我們很容易觀察到質(zhì)因子中2的個數(shù)總是大于等于5的個數(shù)。因此只要計數(shù)5的個數(shù)就可以了。那么怎樣計算n!的質(zhì)因子中所有5的個數(shù)呢?一個簡單的方法是計算floor(n/5)。例如,7!有一個5,10!有兩個5。除此之外,還有一件事情要考慮。諸如25,125之類的數(shù)字有不止一個5。例如,如果我們考慮28!,我們得到一個額外的5,并且0的總數(shù)變成了6。處理這個問題也很簡單,首先對n÷5,移除所有的單個5,然后÷25,移除額外的5,以此類推。下面是歸納出的計算后綴0的公式。
n!后綴0的個數(shù) = n!質(zhì)因子中5的個數(shù)= floor(n/5) + floor(n/25) + floor(n/125) + .... class Solution { public:int trailingZeroes(int n) {int result = 0;while(n){result += n/5;n /= 5;}return result; } };#include<iostream> #include<algorithm> using namespace std; int getnum(int); int main() {int a[] = { 12, 35, 7, 79, 36 };for (auto data : a){cout << data << ' ' << getnum(data) << endl;}system("pause");return 0; }int getnum(int n) {int num = 0;/*while (n){num = num + n / 5;n = n / 5;}return num;*/int j;for (int i = 1; i <= n; i++){j = i;while ((j%5)== 0){j /= 5;num++;}}return num; }
總結(jié)
以上是生活随笔為你收集整理的Factorial Trailing Zeroes的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Majority Element
- 下一篇: 矩阵是怎样变换向量的