标签:
Description
Input
Output
Sample Input
10 10 10 5 25 6
Sample Output
8 4 2
题意:求C(n,m)的最后一位非零数。
思路:弱刚开始搞数学,这些入门题就已经搞的死死的,参考的巨巨的思路和代码,Orz,附链接求阶乘最后一位非零数
相当于求n!/(n-m)!的最后一位非零数,首先先得明白n!的最后一位非零数怎么求,例如对10!:
step1:首先将10!中所有2,5因子去掉;
step2:然后求出剩下的一串数字相乘后末尾的那个数。 (重点)
step3:由于去掉的2比5多,最后还要考虑多余的那部分2对结果的影响。
step4:output your answer!
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <set>
#include <queue>
#include <stack>
#include <map>
using namespace std;
typedef long long LL;
const int inf=0x3f3f3f3f;
const double pi= acos(-1.0);
int get_2(int x)//计算阶乘中质因子2的出现次数
{
if(x==0)
return 0;
else
return (x/2+get_2(x/2));
}
int get_5(int x)//计算阶乘中质因子5的出现次数
{
if(x==0)
return 0;
else
return (x/5+get_5(x/5));
}
int get(int n,int x)//计算f(1) to f(n) 中,奇数数列中末尾为x的数出现的次数
{
if(n==0)
return 0;
else
return (n/10+(n%10>=x)+get(n/5,x));
}
int get_f(int n,int x)//计算f(1) to f(n)中,末尾为x的数的出现次数
{
if(n==0)
return 0;
return get_f(n/2,x)+get(n,x);
}
int mp[4][4]={
{6,2,4,8},//2^n%10的循环节,注意如果2的个数为0时候,结果应该是1,要特殊处理。
{1,3,9,7},//3
{1,7,9,3},//7
{1,9,1,9}//9
};//3,7,9的循环节中第一位,刚好是1,故不需要考虑这些数字出现次数为0的情况。
int main()
{
int n,m;
int res;
while(~scanf("%d %d",&n,&m)){
int n2=get_2(n)-get_2(n-m);
int n5=get_5(n)-get_5(n-m);
int n3=get_f(n,3)-get_f(n-m,3);
int n7=get_f(n,7)-get_f(n-m,7);
int n9=get_f(n,9)-get_f(n-m,9);
res=1;
if(n5>n2){
printf("5\n");
}
else{
if(n2!=n5){
res*=mp[0][(n2-n5)%4];
res%=10;
}
//如果num2==num5,那么2^0次方mod 10应该为1 ,而不是table中的6,所以要特殊处理。
res*=mp[1][n3%4];
res%=10;
res*=mp[2][n7%4];
res%=10;
res*=mp[3][n9%4];
res%=10;
printf("%d\n",res);
}
}
return 0;
}
POJ 1150-The Last Non-zero Digit(求阶乘最后一位非零数)
标签:
原文地址:http://blog.csdn.net/u013486414/article/details/44891169