一个整数n的阶乘可以写成n!,它表示从1到n这n个整数的乘积。阶乘的增长速度非常快,例如,13!就已经比较大了,已经无法存放在一个整型变量中;而35!就更大了,它已经无法存放在一个浮点型变量中。因此,当n比较大时,去计算n!是非常困难的。幸运的是,在本题中,我们的任务不是去计算n!,而是去计算n!最右边的那个非0的数字是多少。例如,5!=1*2*3*4*5=120,因此5!最右边的那个非0的数字是2。再如,7!=5040,因此7!最右边的那个非0的数字是4。再如,15!= 1307674368000,因此15!最右边的那个非0的数字是8。请编写一个程序,输入一个整数n(0<n<=100),然后输出n!最右边的那个非0的数字是多少。
输入:
7
输出:
4
解题思路
这题很容易就爆了,但是由于数据问题,也可以水过去。但是也有其他办法,就是把2、5因子提取出来去掉,然后去取模。就不会有奇怪的进位问题了,eg:12*5=60;
(水)代码
#include <iostream>//数据输入输出流
#include <string.h>//字符串操作函数
#include <stdio.h>//C的输入输出
#include <stdlib.h>//定义杂项函数及内存分配函数
#include <math.h>//C中的数学函数
#include <vector>//STL vetor容器
#include <list>//STL list
#include <map>// STL map
#include <queue>// STL queue
#include <stack>//sTL stack
#include <algorithm>//STL各种算法 比如 swap sort merge max min 比较
#include <numeric>//常用数字操作 一般和algorithm搭配使用
using namespace std;
typedef long long ll;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int maxn = 104;
int main(){
int n,i,num;
scanf("%d",&n);
num=1;
for(i=1;i<=n;i++){
num*=i;
while(num%10==0){/*如果是10的倍数,就一直除10*/
num/=10;
}
num%=1000; /*如果是100,就会被卡住,有一个评测点过不去*/
}
/*其实这题还是水过去的*/
printf("%d\n",num%10);
return 0;
}
AC代码
#include <iostream>//数据输入输出流
#include <string.h>//字符串操作函数
#include <stdio.h>//C的输入输出
#include <stdlib.h>//定义杂项函数及内存分配函数
#include <math.h>//C中的数学函数
#include <vector>//STL vetor容器
#include <list>//STL list
#include <map>// STL map
#include <queue>// STL queue
#include <stack>//sTL stack
#include <algorithm>//STL各种算法 比如 swap sort merge max min 比较
#include <numeric>//常用数字操作 一般和algorithm搭配使用
using namespace std;
typedef long long ll;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int maxn = 104;
int main(){
int n,i,num,a[maxn];
scanf("%d",&n);
num=1;
/*初始化各个值*/
for(i=1;i<=n;i++){
a[i]=i;
}
int countFive=0;/*记录5因子的个数*/
for(i=5;i<=n;i+=5){
while(a[i]%5==0){
a[i]/=5;
countFive++;
}
}
/*去掉相同的2的个数*/
for(i=2; i/2<=countFive; i+=2){
a[i]/=2;
}
/*最后计算结果*/
for(i=2;i<=n;i++){
num*=a[i];
while(num%10==0){
num/=10;
}
num%=10;
}
printf("%d\n",num);
return 0;
}