#include <bits/stdc++.h>
using ll = long long;
using namespace std;
template <class T>
inline void setmin(T& a, T const& b) {
  a = min(a, b);
}
ll solve(ll n, ll m, ll a, ll b, ll p, ll q) {
  if (a == 1 and b == 1) {
    ll delta = p + q;
    ll result = m;
    setmin(result, m - min(n, m / delta) * delta);
    setmin(result, m - min(n, (m + delta - 1) / delta) * delta);
    return result;
  }
  vector<ll> tickets;
  for (int k = 0; (k) < int(n); ++(k)) {
    double estimated = p * pow(a, k) + q * pow(b, k);
    if (2 * m + 3 < estimated) break;
    ll ticket = estimated;
    tickets.push_back(ticket);
  }
  if (tickets.empty()) {
    return m;
  } else if (tickets.size() == 1) {
    return min(m, abs(m - tickets[0]));
  }
  auto generate = [&](int l, int r) {
    vector<ll> acc;
    acc.push_back(0);
    for (int k = (l); (k) < int(r); ++(k)) {
      ll ticket = tickets[k];
      int prev_size = acc.size();
      for (int i = 0; (i) < int(prev_size); ++(i)) {
        acc.push_back(acc[i] + ticket);
      }
      ([&](decltype((acc)) whole) { return (sort)(begin(whole), end(whole)); })(
          acc);
      acc.erase(([&](decltype((acc)) whole) {
                  return (unique)(begin(whole), end(whole));
                })(acc),
                acc.end());
    }
    return acc;
  };
  vector<ll> lower = generate(0, tickets.size() / 2);
  vector<ll> upper = generate(tickets.size() / 2, tickets.size());
  ll result = m;
  for (ll x : lower) {
    int i = ([&](decltype((upper)) whole) {
              return (lower_bound)(begin(whole), end(whole), m - x);
            })(upper)-upper.begin();
    for (int j = (max(0, i - 3)); (j) < int(min<int>(upper.size(), i + 3));
         ++(j)) {
      ll y = upper[j];
      setmin(result, abs(m - (x + y)));
    }
  }
  return result;
}
int main() {
  ll n, m, a, b, p, q;
  scanf("%lld%lld%lld%lld%lld%lld", &n, &m, &a, &b, &p, &q);
  ll result = solve(n, m, a, b, p, q);
  printf("%lld\n", result);
  return 0;
}
