#include using namespace std; typedef long long int ll; typedef pair P; typedef vector VI; typedef vector VVI; #define REP(i,n) for(int i=0;i<(n);i++) #define ALL(v) v.begin(),v.end() template bool chmax(T &x, const T &y){return (x bool chmin(T &x, const T &y){return (x>y)?(x=y,true):false;}; constexpr ll MOD=998244353; constexpr ll INF=2e18; int main(){ ll n, k, seed, a, b, m; cin >> n >> k >> seed >> a >> b >> m; VI f(2*n); f[0]=seed; REP(i,2*n-1) f[i+1]=(f[i]*a+b)%m; VVI v(3); REP(i,n){ ll w=f[i]%3+1; v[w-1].push_back(w*f[n+i]); } VVI s(3); REP(i,3){ sort(ALL(v[i]),greater()); s[i].resize(v[i].size()+1); s[i][0]=0; REP(j,(int)v[i].size()){ s[i][j+1]=s[i][j]+v[i][j]; } } VI x(k+1,0); int pi=0, pj=0; for(int i=1;i<=k;i++){ pi+=3; x[i]=s[0][min(max(0,pi),(int)s[0].size()-1)]+s[1][min(max(0,pj),(int)s[1].size()-1)]; while(1){ ll l=s[0][min(max(0,pi-2),(int)s[0].size()-1)]+s[1][min(max(0,pj+1),(int)s[1].size()-1)]; ll r=s[0][min(max(0,pi+2),(int)s[0].size()-1)]+s[1][min(max(0,pj-1),(int)s[1].size()-1)]; if(pi-2>=pj&&chmax(x[i],l)) pi-=2, pj+=1; else if(pj>=1&&chmax(x[i],r)) pi+=2, pj-=1; else break; } } ll ans=0; REP(i,k+1){ chmax(ans,s[2][min(i,(int)s[2].size()-1)]+x[k-i]); } cout << ans << endl; return 0; }