算法练习:Sequence II

Description
You are given a recurrent formula for a sequence f:
f( n) = 1 + f(1) g(1) + f(2) g(2) + … + f( n−1) g( n−1),
where g is also a recurrent sequence given by formula
g( n) = 1 + 2 g(1) + 2 g(2) + 2 g(3) + … + 2 g( n−1) − g( n−1) g( n−1).
It is known that f(1) = 1, g(1) = 1. Your task is to find f( n) mod  p.


Input
The input consists of several cases. Each case contains two numbers on a single line. These numbers are n (1 ≤  n ≤ 10000) and p (2 ≤  p ≤ 2·10 9). The input is terminated by the case with n = p = 0 which should not be processed. The number of cases in the input does not exceed 5000.


Output
Output for each case the answer to the task on a separate line.


Sample Input
input         output

1 2                 1
2 11               2
0                    0


这道题如果用递归来做会导致运行时间过长,最终报错。一开始用递归分别求出g(n)和f(n),但当n增大到一定数后程序就运行很久,所以行不通。后来发现原来g(n)=n,然后通过f(n)和f(n-1)相减得出f(n)=n*f(n-1),所以f(n)即为n的阶乘。所以题目要求的是n的阶乘取模。这里又有一个问题,n的阶乘结果会很大,可能会超过long long,所以不能算出n!后再取模,可以利用以下公式:(a*b)%c=((a%c)*(b%c))%c。【(a+b)%c=((a%c)+(b%c))%c减法类似】

则有f(n)%p=n!%p=(n*(n-1)!)%p=((n%p)*((n-1)!%p))%p。可以设f(n)%p为m(n),则m(n)=(n*m(n-1))%p,这里的n%p=n是因为当n<p时,n%p必定等于n,当n=p时,理论上m(n)=0,此时m(n)=(n*m(n-1))%p=(p*m(n-1))%p=0,所以公式正确,后面大于p时m(n)也必定等于0,因为前面m(p)=0,所以m(p)*n=0,则m(n)=(n*m(p))%p=0,公式也正确,以此向后推,n%p直接取为n是没有问题的。  

代码如下:

<span style="font-size:14px;">#include <iostream>

using namespace std;

int main()
{
    long long n = 0;
    long long p = 0;
    long long m[10010];
    m[1] = 1;
    for(;;) {
        cin>>n>>p;
        if (n == 0 && p == 0)
            break;
        else {
            for(int i = 2; i <= n; i++) {
                m[i] = (m[i-1] * i) % p;
            }
            cout<<m[n]<<endl;
        }
    }
    return 0;
}</span>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值