ZOJ 2674 Strange Limit

Strange Limit Time Limit: 5 Seconds      Memory Limit: 32768 KB

Consider sequence an defined with the following recurrence:

a1= p,
an+1= pan
for n >= 1,

where p is some prime number. Let

bn = an mod m!,

where m! denotes m factorial, that is m! = 1 · 2 · ... · m.

It may seem strange, but for all p and all m the sequence bn has limit as n . Your task is to find it. Given p and m, find

Input

There are several test cases in the input. Each case contains p and m ( 2 <= p, m <= 12, p is prime). There is am empty line between each case.

Output

Output the limit requested. There should be am empty line between each case.

Example

Input Output
2 2 0
2 3 4
3 8 30267

Source: Andrew Stankevich's Contest #8


大体题意:

给你两个数p,m,计算bn的极限,其中bn等于an对m的阶乘取模,而an = p^p^p...

其实是水过的,n趋向无穷大,就是有无数个p,那么只要让n稍微大一点,就差不多不变了,就是接近无穷大了,所以直接快速幂对m阶乘取模不就可以啦!就是多套几个快速幂就可以求出“极限”,打表就行了。!

正解学会了 在修改!

代码如下:


#include<cstdio>
#include<iostream>
using namespace std;
typedef long long ll;
ll fac(ll n){if (!n)return 1;return n*fac(n-1);}// 求阶乘
ll my_pow(ll a,ll n,ll mod){ll ans = 1;while(n){if (n % 2)ans = (ans * a)%mod;a = (a%mod*a%mod)%mod;n/=2;}return ans;}// 快速幂!对m的阶乘取模
int main()
{
    ll m1=3,m2=4,n,k, p[6] = {2,3,5,7,11},a[50][50];
    for (int k = 0; k < 5; ++k){
        for (ll m2 = 2; m2 <=12; ++m2){
            m1=p[k];
            a[m1][m2]=my_pow(m1,my_pow(m1,my_pow(m1,my_pow(m1,my_pow(m1,my_pow(m1,my_pow(m1,m1,fac(m2)),fac(m2)),fac(m2)),fac(m2)),fac(m2)),fac(m2)),fac(m2));//多套几个快速幂 就是“无穷大”了!
        }
    }
    int cnt = 0;
    while(cin >> n >> k){
        cnt++;
        if (cnt > 1)cout << endl;//注意格式!
        cout << a[n][k] << endl;
    }
    return 0;
}


你可能感兴趣的:(C语言,ZOJ)