#include //#include using namespace std; //using namespace atcoder; //using mint = modint998244353; //const int mod = 998244353; //using mint = modint1000000007; //const int mod = 1000000007; //const int INF = 1e9; const long long LINF = 1e18; #define rep(i, n) for (int i = 0; i < (n); ++i) #define rep2(i,l,r)for(int i=(l);i<(r);++i) #define rrep(i, n) for (int i = (n-1); i >= 0; --i) #define rrep2(i,l,r)for(int i=(r-1);i>=(l);--i) #define all(x) (x).begin(),(x).end() #define allR(x) (x).rbegin(),(x).rend() #define P pair template inline bool chmax(A & a, const B & b) { if (a < b) { a = b; return true; } return false; } template inline bool chmin(A & a, const B & b) { if (a > b) { a = b; return true; } return false; } long long Ternarysearch() { long long a, b; std::cin >> a >> b; long long r = LINF; long long l = 0; auto f = [&](long long x)->long long { return (double)a / sqrt(1.0 + x) + (double)b * x; }; // 上に凸 while (2 < abs(r - l)) { long long ml = (l * 2 + r) / 3; long long mr = (l + r * 2) / 3; if (f(ml) > f(mr)) r = mr; else l = ml; } long long ret = -LINF; for (long long i = l; i <= r; ++i)ret = std::max(ret, f(i)); return ret; } int f0(int s1, int s2) { if (s1 >= s2) { return s2 + (s1 - s2) / 3; } return s1; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n, k; long long seed, a, b, m; cin >> n >> k >> seed >> a >> b >> m; vectorw(n), v(n); vectorf(n * 2); f[0] = seed; rep2(i, 1, n * 2) f[i] = (a * f[i - 1] + b) % m; rep(i, n) { w[i] = f[i] % 3 + 1; v[i] = w[i] * f[i + n]; } vector item(4, vector()); rep(i, n)item[w[i]].push_back(v[i]); rep(i, 4)sort(allR(item[i])); vector itemSum(4, vector()); rep(i, 4) { itemSum[i].resize(item[i].size() + 1); rep(j, item[i].size()) itemSum[i][j + 1] = itemSum[i][j] + item[i][j]; } long long ans = 0; int tmp = f0(item[1].size(), item[2].size()); rep(i, min((int)item[3].size(), k) + 1) {// 3の数を全探索する long long val = itemSum[3][i] - itemSum[3][0]; int j = min(k - i, tmp); { int r = item[2].size();// 2を使う数 int l = 0; auto f = [&](int x)->long long { int y = (k - i) * 3 - x * 2; if (x > item[2].size())return -LINF; if (y > item[1].size())return -LINF; long long ret = 0; ret += itemSum[1][y] - itemSum[1][0]; ret += itemSum[2][x] - itemSum[2][0]; return ret; }; // 上に凸 while (2 < abs(r - l)) { int ml = (l * 2 + r) / 3; int mr = (l + r * 2) / 3; if (f(ml) > f(mr)) r = mr; else l = ml; } long long ret = -LINF; for (int i = l; i <= r; ++i) ret = std::max(ret, f(i)); chmax(ans,val + ret); } } cout << ans << endl; return 0; }