Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

说下思路,贴代码

Posted by dahai1990 at 2012-04-14 11:20:11 on Problem 3406
这一题和1150很像,不过好像用1150的思路的话会比较复杂.考虑到数据范围没有1150的大,我就
把原来1150超时的做法改了下,果然AC了.
思路:求N!的最后非零数字.将1~N进行分解,不过只是分解成2,3,5,7,9的幂次乘以一个数,
并且用数组d[]记录它们的幂次,其中最后一个数只要记录成末尾数字就行了.比如
156=2^2*3*13,就记录成d[2]+=2,d[3]+=1,d[13%10]=d[3]+=1;

#include <stdio.h>
#include <memory.h>
int d[10];
int pow_mod(int a,int n,int m)
{
	if(n==0) return 1;
	n=(n-1)%4;
	int ans=1;
	for(int i=0;i<=n;i++) ans*=a;
	return ans%m;
}
void factor(int x,int delt)
{
	while(x%2==0) { d[2]+=delt; x/=2; }
	while(x%3==0) { d[3]+=delt; x/=3; }
	while(x%5==0) { d[5]+=delt; x/=5; }
	while(x%7==0) { d[7]+=delt; x/=7; }
	while(x%9==0) { d[9]+=delt; x/=9; }
	d[x%10]+=delt;
}
int main()
{
	int n,m,ans,t,i;
	while(scanf("%d%d",&n,&m)!=EOF)
	{
		memset(d,0,sizeof(d));
		for(i=n-m+1;i<=n;i++) factor(i,1);
		for(i=1;i<=m;i++) factor(i,-1);
		t=d[2]<d[5]?d[2]:d[5];
		d[2]-=t; d[5]-=t;
		ans=pow_mod(2,d[2],10);
		ans*=pow_mod(3,d[3],10);
		ans*=pow_mod(7,d[7],10);
		ans*=pow_mod(9,d[9],10);
		if(d[5]) ans*=5;
		printf("%d\n",ans%10);
	}
	return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator