zoukankan      html  css  js  c++  java
  • (大幂分解求和)A^X mod P(数的高次幂)

    It's easy for ACMer to calculate A^X mod P. Now given seven integers n, A, K, a, b, m, P, and a function f(x) which defined as following.

    f(x) = K, x = 1

    f(x) = (a*f(x-1) + b)%m , x > 1



    Now, Your task is to calculate

    ( A^(f(1)) + A^(f(2)) + A^(f(3)) + ...... + A^(f(n)) ) modular P. 

    输入

    In the first line there is an integer T (1 < T <= 40), which indicates the number of test cases, and then T test cases follow. A test case contains seven integers n, A, K, a, b, m, P in one line.

    1 <= n <= 10^6

    0 <= A, K, a, b <= 10^9

    1 <= m, P <= 10^9

    输出

    For each case, the output format is “Case #c: ans”. 

    c is the case number start from 1.

    ans is the answer of this problem.

    样例输入 Copy

    2
    3 2 1 1 1 100 100
    3 15 123 2 3 1000 107
    

    样例输出 Copy

    Case #1: 14
    Case #2: 63


    就是预先把A的次幂处理出来

    dp1数组构造A^0~A^(10^5),间隔为A。

    
    

    dp2数组构造A^(10^5)~A^(10^10),间隔为A^(10^5)。

    
    

    这样对于任意的A^x就能表示成dp2[x/(10^5)]*dp1[x%(10^5)]

    
    

    从而用空间换取时间。

    如果是A的1e4次幂,表示为dp2[0]*dp1[1e4]=dp1[1e4]

    如果是A的1e6次幂,表示为dp2[10]*dp1[0]

    如果是A的1e6+10次幂,表示为dp2[10]*dp[10]=A的1e6次幂乘A的10次幂,就是A的1e6+10次幂

    #include<bits/stdc++.h>
    using namespace std;
    typedef long long ll;
    const int maxn=1e5;
    ll f1[110011];
    ll f2[110011];
    ll n,A,k,a,b,m,p;
    void inint(){
        f1[0]=f2[0]=1;
        f1[1]=A%p;
        for(int i=2;i<=maxn;i++){
            f1[i]=(f1[i-1]*f1[1])%p;
        }
        f2[1]=f1[maxn];
        for(int i=2;i<=maxn;i++){
            f2[i]=(f2[i-1]*f2[1])%p;
        }
    } 
    int main(){
        int t;
        cin>>t;
        for(int case1=1;case1<=t;case1++){
            cin>>n>>A>>k>>a>>b>>m>>p;
            inint();
            ll ans=0;
            ll z=k;
            for(int i=1;i<=n;i++){
                ans=(ans+f2[z/maxn]*f1[z%maxn])%p;
                z=(a*z+b)%m;
            }
            printf("Case #%d: %lld
    ",case1,ans);
        }
    }
    
    
  • 相关阅读:
    查看MySQL数据库表的命令介绍
    MySQL 数据库常用命令 超级实用版分享
    从cmd中进入MySQL的命令界面
    POJ-1664 放苹果
    ant常用命令
    ant来历
    ant
    ant有什么用
    ANT的安装和配置(windows)
    Experimental Educational Round: VolBIT Formulas Blitz B
  • 原文地址:https://www.cnblogs.com/lipu123/p/13649145.html
Copyright © 2011-2022 走看看