#include using namespace std; //#include //using namespace atcoder; using ll = long long int; using ull = unsigned long long int; using ld = long double; constexpr ll MAX = 2000000000000000000; constexpr ld PI = 3.14159265358979; constexpr ll MOD = 0;//2024948111; ld dotorad(ld K){ return PI * K / 180.0; } ld radtodo(ld K){ return K * 180.0 / PI; } mt19937 mt; void randinit(){ srand((unsigned)time(NULL));mt = mt19937(rand()); } int main(){ ll N,A,B,C; cin >> N >> A >> B >> C; vector fac(N + 2,1),fac_b(N + 2,1); for(ll i = 1;i <= N;i++) fac[i] = (fac[i - 1] * i) % N; for(ll i = 1;i <= N;i++){ fac_b[i] = (fac_b[i - 1] * i); if(fac_b[i] > N) fac_b[i] = N; } priority_queue,vector>,greater>> que; que.emplace(0,1); vector memo(N + 2,MAX); while(!que.empty()){ auto [cost,now] = que.top(); que.pop(); if(memo[now] == MAX){ memo[now] = cost; que.emplace(cost + A,(now + 1) % N); ll x = 1,c = 1; for(ll i = 1;i < 60;i++){ x *= now; x %= N; if(MAX / c < B) break; c *= B; que.emplace(cost + c,x); } que.emplace(cost + C,fac[now]); } } vector memo2(N + 2,MAX); que.emplace(0,1); while(!que.empty()){ auto [cost,now] = que.top(); que.pop(); if(memo2[now] == MAX){ memo2[now] = cost; que.emplace(cost + A,(now + 1)); ll x = 1,c = 1; for(ll i = 1;i < 60;i++){ x *= now; x = min(x,N); if(MAX / c < B) break; c *= B; que.emplace(cost + c,min(x,N)); } que.emplace(cost + C,fac_b[now]); } } cout << min(memo[0],memo2[N] + C) << endl; }