Consider an array A with N elements, all being the same integer a.
Define the product transformation as a simultaneous update Ai = Ai·Ai + 1, that is multiplying each element to the element right to it for , with the last number AN remaining the same. For example, if we start with an array A with a = 2 and N = 4, then after one product transformation A = [4, 4, 4, 2], and after two product transformations A = [16, 16, 8, 2].
Your simple task is to calculate the array A after M product transformations. Since the numbers can get quite big you should output them modulo Q.
The first and only line of input contains four integers N, M, a, Q (7 ≤ Q ≤ 109 + 123, 2 ≤ a ≤ 106 + 123, , is prime), where is the multiplicative order of the integer a modulo Q, see notes for definition.
You should output the array A from left to right.
2 2 2 7
1 2
The multiplicative order of a number a modulo Q , is the smallest natural number x such that ax mod Q = 1. For example, .
#include<stdio.h>
#include<algorithm>
#include<string.h>
#define N 1000000+130
using namespace std;
typedef long long ll;
int n, m, a, Q, X;
ll fac[N], inv[N], c[N];
void factorial()
{
int top = 1e6 + 123;
fac[0] = 1; for(int i = 1; i <= top; i ++) fac[i] = fac[i - 1] * i % X;
inv[0] = inv[1] = 1; for(int i = 2; i <= top; i ++) inv[i] = inv[X % i] * (X - X / i) % X;
for(int i = 2; i <= top; i ++) inv[i] = inv[i] * inv[i - 1] % X;
}
ll C(int n, int m)
{
return fac[n] * inv[m] % X * inv[n - m] % X;
}
ll quick(ll a,ll b,ll M)
{
ll c=1;
while(b)
{
if(b&1)c=c*a%M;
a=a*a%M;
b>>=1;
}
return c;
}
ll ans[N];
int main ()
{
scanf("%d%d%d%d",&n,&m,&a,&Q);
X=1;
while(quick(a,X,Q)!=1)X++;
factorial();
for(int i=1;i<=m+1;i++){
c[i]=C(m,i-1);
c[i]=(c[i]+c[i-1])%X;
}
for(int i=n;i;i--){
if(n-i+1<=m+1)ans[i]=c[n-i+1];
else ans[i]=ans[i+1];
}
for(int i=1;i<n;i++)
printf("%lld ",quick(a,ans[i],Q));
printf("%lld\n",quick(a,ans[n],Q));
return 0;
}