codevs 1281 Xn数列

时间:2021-07-13 03:13:39

题目描述 Description

给你6个数,m, a, c, x0, n, g

Xn+1 = ( aXn + c ) mod m,求Xn

m, a, c, x0, n, g<=10^18

输入描述 Input Description

一行六个数 m, a, c, x0, n, g

输出描述 Output Description

输出一个数 Xn mod g

样例输入 Sample Input

11 8 7 1 5 3

样例输出 Sample Output

2

  很久没有写博客了……先写道水题压压惊

  由于不想写矩乘(不要问我为什么),所以我就开始了推式子(其实就是想当做数学题来做)。

  首先,由于$x_i=ax_{i-1}+c$,那么$x_n={a^nx_0+\sum_{i=0}^{n-1}a^ic}$

  那么,写个快速幂,前面一部分就出来了。再设$f_x=\sum_{i=0}^{x}a^i$,$y=\lfloor x/2 \rfloor$,那么有:

$$ f_x= \begin{cases} (a^{y+1}+1)f_{y} &(x \bmod 2=1) \\ f_{x-1}+a^x&(x \bmod 2=0) \end{cases} $$

  最后,由于模数是$10^{18}$级别的,还要写个快速乘法。

  下面贴代码(好像一不小心多写了若干个$\log$):

 #include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#define File(s) freopen(s".in","r",stdin),freopen(s".out","w",stdout) using namespace std;
typedef long long llg; llg m,a,c,x0,g,n,ans; void gi(llg &h){if(h>=m) h%=m;}
llg ch(llg a,llg b){
llg s=;
if(a<b) swap(a,b);
while(b){
if(b&) s+=a,gi(s);
a<<=,gi(a); b>>=;
}
return s;
} llg mi(llg a,llg b){
llg s=;
while(b){
if(b&) s=ch(s,a);
a=ch(a,a); b>>=;
}
return s;
} llg solve(llg x){
if(!x) return ;
llg s,u=(x-)>>;
s=ch(solve(u),mi(a,u+)+);
if(!(x&)) s+=mi(a,x),gi(s);
return s;
} int main(){
scanf("%lld %lld %lld %lld %lld %lld",&m,&a,&c,&x0,&n,&g);
ans=ch(mi(a,n),x0);
ans+=ch(solve(n-),c); gi(ans);
printf("%lld",ans%g);
return ;
}