N,K,seed,a,b,m=map(int,input().split()) w=[0]*N f=seed for i in range(N): w[i]=f%3+1 f=(a*f+b)%m v=[0]*N for i in range(N): v[i]=f*w[i] f=(a*f+b)%m w1=[0]*3*K w2=[0]*K w3=[0]*K for i in range(N): if w[i]==1: w1.append(v[i]) if w[i]==2: w2.append(v[i]) if w[i]==3: w3.append(v[i]) w1.sort(reverse=True) w2.sort(reverse=True) w3.sort(reverse=True) ans=0 res=[0] idx1=0 idx2=0 tmp=0 for i in range(1,K+1): tmp+=w1[idx1]+w1[idx1+1]+w1[idx1+2] idx1+=3 while idx2=w1[idx1-1]+w1[idx1-2]: tmp+=w2[idx2]-w1[idx1-1]-w1[idx1-2] idx2+=1 idx1-=2 while idx2>0 and w1[idx1]+w1[idx1+1]>=w2[idx2-1]: tmp+=w1[idx1]+w1[idx1+1]-w2[idx2-1] idx2-=1 idx1+=2 res.append(tmp) cum3=0 for i in range(K+1): ans=max(ans,res[K-i]+cum3) cum3+=w3[i] print(ans)