#include<bits/stdc++.h>
#define X begin()
#define Y end()
#define N 41
using namespace std;
typedef long long ll;
ll n,m,a,b,p,q,d[N];
vector<ll> v[2],x[2];

int main(){
  cin>>n>>m>>a>>b>>p>>q;
  ll ans=m; p+=q;
  if(a==1&&b==1){
    ll ti=min(n,m/p);
    ans=min(ans,min(m-ti*p,abs(min(ti+1,n)*p-m)));
  }
  ll A=1,B=1,T=min((ll)N,n);
  for(int i=0;i<T;i++){
    d[i]=p*A+q*B;
    if(i<T/2)v[0].push_back(d[i]);
    else v[1].push_back(d[i]);
    if(d[i]>m)break;
    A*=a,B*=b;
  }
  int len[2]={v[0].size(),v[1].size()};
  for(int i=0;i<2;i++){
    v[i].push_back(0);
    for(int j=0;j<(1<<len[i]);j++){
      ll sum=0;
      for(int k=0;k<len[i];k++)
	if((j&(1<<k)))sum+=v[i][k];
      x[i].push_back(sum);
    }
    sort(x[i].X,x[i].Y);
  }
  for(int i=0;i<x[0].size();i++){
    ll S=m-x[0][i];
    vector<ll>::iterator r=lower_bound(x[1].X,x[1].Y,S);
    if(r!=x[1].Y)ans=min(ans,(*r)-S);
    if(r!=x[1].X)ans=min(ans,S-(*(r-1)));
  }
  cout<<ans<<endl;
  return 0;
}