#include using namespace std; using ll = long long; #define rep(i,n) for(int i=0;i<(int)(n);i++) ll mpow(ll x,ll n,ll m){ ll res=1; while(n>0){ if(n&1) res=res*x%m; x=x*x%m; n>>=1; } return res; } int main(){ ll n,a,b,c; cin>>n>>a>>b>>c; vector fac(n+1,1); ll ud=-1; for(ll i=2;i<=n;i++){ if(ud==-1){ fac.at(i)=fac.at(i-1)*i; if(fac.at(i)>=n){ ud=i; fac.at(i)%=n; } }else{ fac.at(i)=fac.at(i-1)*i%n; } } ll mxc=n*a; vector cs(n+1,1e18); priority_queue,vector>,greater>> pq; pq.push({0,1}); while(!pq.empty()){ auto[sc,v]=pq.top(); pq.pop(); if(cs.at(v)!=1e18) continue; cs.at(v)=sc; if(v==n) break; if(v==0){ pq.push({sc+c,n}); continue; } if(cs.at(v+1)==1e18){ pq.push({sc+a,v+1}); } { int k=1; ll bf=-1; while(1){ int nx=mpow(v,k,n); ll pw=mpow(b,k,mxc); if(pw=mxc) break; bf=pw; if(cs.at(nx)==1e18){ pq.push({sc+pw,nx}); } k++; } } { int nx=fac.at(v); if(nx==0) nx=n; if(cs.at(nx)==1e18){ pq.push({sc+c,nx}); } if(ud<=v&&cs.at(0)==1e18){ pq.push({sc+c,0}); } } } cout<