#include <iostream>
#include <sstream>
#include <iomanip>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <algorithm>
#include <numeric>
#include <iterator>
#include <functional>
#include <complex>
#include <queue>
#include <stack>
#include <cmath>
#include <cassert>
#include <tuple>
using namespace std;
typedef long long LL;
typedef complex<double> CMP;

class PackingBallsDiv1 { public:
	int minPacks(int K, int A, int B, int C, int D)
	{
		vector<int> X(K);
		X[0] = A;
		for(int i=1; i<K; ++i)
			X[i] = int((LL(X[i-1]) * B + C) % D + 1);

		int base = 0;
		for(int i=0; i<K; ++i) {
			base += X[i] / K;
			X[i] %= K;
		}
		sort(X.begin(), X.end());

		int i = 0; while(i<X.size() && X[i]==0) i++;

		int best = base + X.size()-i;
		for(; i<X.size(); ++i)
			best = min<int>(best, base + X[i] + X.size()-i-1);
		return best;
	}
};

// BEGIN CUT HERE
#include <ctime>
double start_time; string timer()
 { ostringstream os; os << " (" << int((clock()-start_time)/CLOCKS_PER_SEC*1000) << " msec)"; return os.str(); }
template<typename T> ostream& operator<<(ostream& os, const vector<T>& v)
 { os << "{ ";
   for(typename vector<T>::const_iterator it=v.begin(); it!=v.end(); ++it)
   os << '\"' << *it << '\"' << (it+1==v.end() ? "" : ", "); os << " }"; return os; }
void verify_case(const int& Expected, const int& Received) {
 bool ok = (Expected == Received);
 if(ok) cerr << "PASSED" << timer() << endl;  else { cerr << "FAILED" << timer() << endl;
 cerr << "\to: \"" << Expected << '\"' << endl << "\tx: \"" << Received << '\"' << endl; } }
#define CASE(N) {cerr << "Test Case #" << N << "..." << flush; start_time=clock();
#define END	 verify_case(_, PackingBallsDiv1().minPacks(K, A, B, C, D));}
int main(){

CASE(0)
	int K = 3; 
	int A = 4; 
	int B = 2; 
	int C = 5; 
	int D = 6; 
	int _ = 4; 
END
CASE(1)
	int K = 1; 
	int A = 58; 
	int B = 23; 
	int C = 39; 
	int D = 93; 
	int _ = 58; 
END
CASE(2)
	int K = 23; 
	int A = 10988; 
	int B = 5573; 
	int C = 4384; 
	int D = 100007; 
	int _ = 47743; 
END
CASE(3)
	int K = 100000; 
	int A = 123456789; 
	int B = 234567890; 
	int C = 345678901; 
	int D = 1000000000; 
	int _ = 331988732; 
END
/*
CASE(4)
	int K = ; 
	int A = ; 
	int B = ; 
	int C = ; 
	int D = ; 
	int _ = ; 
END
CASE(5)
	int K = ; 
	int A = ; 
	int B = ; 
	int C = ; 
	int D = ; 
	int _ = ; 
END
*/
}
// END CUT HERE
