#ifndef ONLINE_JUDGE #define _GLIBCXX_DEBUG #endif #include #include #include using namespace std; using namespace atcoder; using ll = long long; using mint = modint998244353; //using mint = modint1000000007; #define rep(i, n) for (int i = 0; i < (int)(n); i++) #define repu(i, s, t) for (int i = (int)(s); i < (int)(t); i++) #define repd(i, s, t) for (int i = (int)(s)-1; i >= (int)(t); i--) #define all(v) v.begin(), v.end() void _u() { cerr << endl; } template void _u(H&& h, T&&... t) { cerr << h << ", "; _u(move(t)...); } #define U(...) { cerr << #__VA_ARGS__ << ": "; _u(__VA_ARGS__); } template bool chmax(T &a, const T b) { if(a >= b) return false; a = b; return true; } template bool chmin(T &a, const T b) { if(a <= b) return false; a = b; return true; } template istream& operator>>(istream &in, vector &a) { for(T &x: a) in >> x; return in; } template ostream& operator<<(ostream &out, const vector &a) { for(const T &x: a) out << x << ' '; return out; } const int di[] = {1, 0, -1, 0, 1, 1, -1, -1, 0}; const int dj[] = {0, 1, 0, -1, -1, 1, 1, -1, 0}; int main() { cin.tie(0)->sync_with_stdio(0); int n, a, b, c; cin >> n >> a >> b >> c; const int INF = 1e7; vector bs(2); bs[1] = b; while(1) { ll tmp = bs.back() * ll(b); if(tmp >= INF) break; bs.push_back(tmp); } vector dp(n+1, INF); dp[1] = 0; int facts = 1, ans = INF; repu(i, 1, n) { chmin(dp[i+1], dp[i] + a); facts = min(ll(INF), ll(facts) * i); if(facts <= n) chmin(dp[facts], dp[i] + c); else chmin(ans, dp[i] + 2*c); int p = i; for(int j = 2; j < bs.size(); j++) { p = min(ll(INF), ll(p)*i); if(p > n) { chmin(ans, dp[i] + bs[j] + c); break; } chmin(dp[p], dp[i] + bs[j]); } } vector dist = dp; dist[0] = dp[n]; facts = 1; repu(i, 1, n) { facts = (ll(facts) * i) % n; chmin(dist[facts], dp[i] + c); } dist.pop_back(); priority_queue, vector>, greater>> pq; rep(i, n) pq.emplace(dist[i], i); auto upd = [&](int to, int nd) { if(dist[to] <= nd) return; dist[to] = nd; pq.emplace(nd, to); }; while(!pq.empty()) { auto[d, pos] = pq.top(); pq.pop(); if(dist[pos] < d) continue; upd((pos+1)%n, a+dist[pos]); int p = pos; repu(i, 2, bs.size()) { p = (ll(p) * pos) % n; upd(p, bs[i]+dist[pos]); } } chmin(ans, dist[0]); cout << ans << endl; return 0; }