X-Sequence

Description

Let {xi} be the infinite sequence of integers: 
1) x0 = A; 
2) xi = (alpha * xi-1^2 + beta * xi-1 + gamma) mod M, for i >= 1. 
Your task is to find xk if you know A, alpha, beta, gamma, M and k.

Input

Given A (1 <= A <= 10000), alpha (0 <= alpha <= 100), beta (0 <= beta <= 100), gamma (0 <= gamma <= 100), M (1 <= M <= 1000), k (0 <= k <= 10^9). All numbers are integer.

Output

Write xk.

Sample Input


Input
 
 
1 1 1 1 10 1
 
 

Output
 
 
3
 
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**********************
打表观察,一个周期问题,暴力找周期 ,巧用map找周期 
********************************/
#include"iostream"
#include"map"
#include"cstdio"
using namespace std;
const int ms=1100;
int T,begin,A,a,b,c,m,k;
void find()
{
    map<int, int> mp; 
    //map[0]=A;
    mp[1]=A; 
    int tmp=A;
    for(int i=2;i<=ms;i++)
    {
        tmp=(a*tmp*tmp+b*tmp+c)%m;
        if(mp[tmp])
        {
            begin=mp[tmp];
            T=i-mp[tmp];
            break;
        }
        else
        {
            mp[tmp]=i;
        }
    }
}
int main()
{
    scanf("%d%d%d%d%d%d",&A,&a,&b,&c,&m,&k);
    find();
    int ans;
    if(k<begin)
    {
        ans=A;
        for(int i=1;i<=k;i++)
            ans=((long long)a*ans*ans+b*ans+c)%m;
        cout<<ans<<endl;
    }
    else
    {
        k-=begin;k%=T;ans=A;
        for(int i=1;i<=begin+k;i++)
        {
            ans=(a*ans*ans+b*ans+c)%m;
        }
        cout<<ans<<endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/767355675hutaishi/p/3849061.html