Code:

#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<string>
using namespace std;
void setIO(string a){ freopen((a+".in").c_str(),"r",stdin); }
#define ll long long
ll mod,g;
int nodes;
struct matrix{
    long long mat[2][2];
}unit,solve,fin;
void init(matrix &a){
    for(int i=0;i<=nodes;++i)
        for(int j=0;j<=nodes;++j) a.mat[i][j]=0;
}
void get(matrix &a){
    init(a);
    for(int i=0;i<=nodes;++i) a.mat[i][i]=1;
}
ll mult(ll a,ll b){
    ll res=0;
    while(b>0){
        if(b&1) res=(res+a)%mod;
        a=(a+a)%mod;
        b>>=1;
    }
    return res;
}
matrix operator*(matrix a,matrix b){
    matrix c;
    init(c);
    for(int i=0;i<=nodes;++i)
        for(int j=0;j<=nodes;++j)
            for(int k=0;k<=nodes;++k) 
                c.mat[i][j]=(c.mat[i][j]+mult(a.mat[i][k],b.mat[k][j]))%mod;
    return c;
}
matrix operator^(matrix a,ll p){
    matrix res;
    get(res);
    while(p>0){
        if(p&1) res=res*a;
        a=a*a;
        p>>=1;
    }
    return res;
}
int main(){
    //setIO("input");
    nodes=1;
    ll a,c,x,n;
    cin>>mod>>a>>c>>x>>n>>g;
    init(unit),init(solve);
    unit.mat[0][0]=a,unit.mat[1][1]=1,unit.mat[1][0]=c;
    solve.mat[0][0]=x,solve.mat[0][1]=1;
    fin=solve*(unit^n);
    cout<<(fin.mat[0][0]%mod)%g;
    return 0;
}