#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using P = pair<ll, ll>;
ll _pow(ll a, ll n) {
  if (n == 0)
    return 1;
  else {
    ll res = 1;
    ll buf = a;
    while (n > 0) {
      if (n % 2 == 1) {
        res *= buf;
      }
      buf *= buf;
      n /= 2;
    }
    return res;
  }
}
void solve() {
  ll n, m, a, b, p, q;
  cin >> n >> m >> a >> b >> p >> q;
  if (n == 1) {
    if (p + q > m)
      cout << m << endl;
    else
      cout << m - (p + q) << endl;
    return;
  }
  ll c = max(a, b);
  if (c == 1) {
    if ((p + q) * n > m) {
      cout << min(m - m / (p + q) * (p + q), (m / (p + q) + 1) * (p + q) - m)
           << endl;
    } else
      cout << m - (p + q) * n << endl;
  } else if (c == 2 || c == 3) {
    ll _n = 0;
    if (c == 2) _n = min(41LL, n);
    if (c == 3) _n = min(29LL, n);
    ll div1 = _n / 2;
    ll div2 = _n - div1;
    vector<ll> d1;
    vector<ll> d2;
    for (ll bit = 0; bit < (ll)(1ll << div1); bit++) {
      bitset<31> bi(bit);
      ll sum = 0;
      for (ll i = 0; i < (ll)div1; i++)
        if (bi[i]) sum += p * _pow(a, i) + q * _pow(b, i);
      d1.push_back(sum);
    }
    for (ll bit = 0; bit < (ll)(1ll << div2); bit++) {
      bitset<31> bi(bit);
      ll sum = 0;
      for (ll i = 0; i < (ll)div2; i++)
        if (bi[i]) sum += p * _pow(a, div1 + i) + q * _pow(b, div1 + i);
      d2.push_back(sum);
    }
    sort(d1.begin(), d1.end());
    sort(d2.begin(), d2.end());
    ll ans = m;
    for (ll i = 0; i < (ll)d1.size(); i++) {
      auto ite = upper_bound(d2.begin(), d2.end(), m - d1[i]);
      if (ite != d2.end()) ans = min(ans, (d1[i] + *ite) - m);
      if (ite == d2.begin()) continue;
      ite--;
      ans = min(ans, m - (d1[i] + *ite));
    }
    cout << ans << endl;
  } else {
    vector<ll> num;
    num.push_back(0);
    num.push_back(p + q);
    for (ll i = 0; i < (ll)min(23LL, n - 1); i++) {
      if (1000000000007LL / (ld)_pow(c, i) < c) break;
      ll val = p * _pow(a, i + 1) + q * _pow(b, i + 1);
      vector<ll> nnum = num;
      for (ll j = 0; j < (ll)num.size(); j++) nnum.push_back(num[j] + val);
      num = nnum;
    }
    sort(num.begin(), num.end());
    num.erase(unique(num.begin(), num.end()), num.end());
    ;
    ll ans = 1000000000ll * 1000000000ll;
    for (ll i = 0; i < (ll)num.size(); i++) ans = min(ans, abs(m - num[i]));
    cout << ans << endl;
  }
}
int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  solve();
  return 0;
}
