#include <bits/stdc++.h>
using namespace std;
using ll = long long;
ll seed, n, p;
ll nextRand()
{
static ll x = seed;
x ^= x << 11;
x ^= x >> 45;
x ^= x << 14;
return (x % p + p) % p;
}
const ll mn = 1e7 + 10;
int lf[mn], rf[mn], vis[mn];
ll ans;
signed main()
{
cin.tie(0)->ios::sync_with_stdio(false);
cin >> n >> p >> seed;
for (ll i = 0; i <= p; ++i)
{
rf[i] = p + 1;
}
for (int i = 0; i < n; ++i)
{
// int cmd, v;cin >> cmd >> v;
int cmd = nextRand() % 4, v = 1 + nextRand();
if (cmd == 0 && !vis[v])
{
lf[v] = lf[rf[v]];
rf[v] = rf[lf[v]];
rf[lf[v]] = lf[rf[v]] = v;
vis[v] = true;
}
else if (cmd == 1 && vis[v])
{
rf[lf[v]] = rf[v];
lf[rf[v]] = lf[v];
vis[v] = false;
}
else if (cmd == 2)
{
ans += vis[v] && lf[v] ? lf[v] : -1;
}
else if (cmd == 3)
{
ans += vis[v] && rf[v] <= p ? rf[v] : -1;
}
}
cout << ans << '\n';
return 0;
}
/*
16 10 10
0 1
0 2
0 4
0 8
0 10
2 1
2 4
2 10
3 1
3 4
3 10
1 5
1 4
3 2
2 8
2 4
*/