2023年9月4日 星期一

[172] Factorial Trailing Zeroes

顯然照著題意先算出費伯那契 (再去算尾巴有幾個零)會overflow  XD
但不管怎樣還是先寫個直覺寫法

long long fac(int n)
{
if (n<=1)
return 1;
return n*fac(n-1);
}

int trailingZeroes(int n){
long long target = fac(n);
int count=0;
while (target %10 == 0)
{
count++;
target = target/10;
}
return count;
}

至於怎麼加速,雖然也有想說以零結尾一定是 2*5 來的 ,階乘中2 又比5多,所以應該是算5 出現了幾次 (吧) 不過我把相乘的概念跟相加的概念一直混在一起,像是 15 是 3*5 它是一個5  ,而不是15 = 5+5+5是三個五吧XD

哎啊我的數學(和前途)勘慮啊XD
int trailingZeroes(int n){
int i=5;
int count=0;
while (n/i > 0)
{
count+= n/(i);
i=i*5;
}
return count;
}


沒有留言:

張貼留言