“求 N 阶乘末尾的第一个非零数字”是一道常见的企业笔试题。这里我们略微做个变化,求 N 阶乘末尾的第一个非零 K 位数,同时输出末尾有多少个零。
输入给出一个不超过 107 的正整数 N 和要求输出的位数 0<K<10。
在一行中输出 N 阶乘末尾的第一个非零 K 位数(注意前导零也要输出)、以及末尾 0 的个数,其间以 1 个空格分隔。
18 5
05728 3
#include <iostream>
#include <algorithm>
#include <stdlib.h>
#include <string.h>
using namespace std;
int countZero(int N){
int ret=0;
while(N>=5){
N/=5;
ret+=N;
}
return ret;
}
int main()
{
int n,k,m;
char t;
long long s=1,p=1;
char str[100];
cin>>n>>k;
for(int i=1;i<=n;i++)
{
s=s*i;
while(s%10==0) s/=10;
s=s%10000000000;
}
// cout<<s<<endl;
for(int i=0;i<k;i++){
if(s){
str[i]=s%10+48;
s/=10;
}
else str[i]='0';
}
for(int i=k-1;i>=0;i--)
cout<<str[i];
cout<<" ";
cout<<countZero(n);
return 0;
}