日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Factorial Trailing Zeroes

發(fā)布時間:2025/4/16 编程问答 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Factorial Trailing Zeroes 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。