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 gemenhao at 2006-04-02 13:51:00 on Problem 1845
难点在于如何求解 1+p+p^2+.....+p^n 对9901求模

设
  fact(n)为上面的表达式
那么
  if n % 2 == 1
     fact(n) = (1+p+p^2+..+p^(n/2))*(1+p^(n/2+1))
             = fact(n/2) * (1+p^(n/2+1))
else
     fact(n) =  fact(n-1) + p^n
             =  1 + p * fact(n-1)
这样就很快了
上面还可以进一步优化,考虑到每次迭代都要求 p^n % 9901
可以把上次计算的 p^(n/2+1) % 9901 预先存贮

int modn(int base,int pow)
用于计算  base^pow % 9901
其他还有快速质因数分解等

int fact(int base, int n)
{
	if(n < 1)
		return 1;
	else
	{
		if(n%2 == 1)
			return ( fact(base,n/2) * (1 + modn(base,n/2+1)) ) % mod;
		else
			return ( fact(base,n-1) + modn(base,n) ) % mod;
                            //or   ( base * fact(base,n-1) + 1 ) % mod;// this is fater
	}
}


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