#include <bits/stdc++.h>
using namespace std;
const long long inf = 1ll << 60;
long long mult(long long a, long long b) {
  if (inf / a < b) throw 0;
  return a * b;
}
int main() {
  long long n, m, a, b, p, q;
  cin >> n >> m >> a >> b >> p >> q;
  if (a == 1 && b == 1) {
    cout << m / (p + q) << endl;
    return 0;
  }
  if (n > 40) n = 40;
  vector<long long> v;
  long long aa = 1;
  long long bb = 1;
  try {
    for (int i = 0; i < (int)(n); i++) {
      long long val = mult(p, aa) + mult(q, bb);
      if (val <= m + m)
        v.push_back(val);
      else
        break;
      aa = mult(aa, a);
      bb = mult(bb, b);
    }
  } catch (int n) {
  }
  vector<long long> as;
  vector<long long> bs;
  n = v.size();
  for (int i = 0; i < (int)(1 << (n / 2)); i++) {
    long long tmp = 0;
    for (int j = 0; j < (int)(n / 2); j++)
      if (i & (1 << j)) tmp += v[j];
    as.push_back(tmp);
  }
  for (int i = 0; i < (int)(1 << (n / 2 + n % 2)); i++) {
    long long tmp = 0;
    for (int j = 0; j < (int)(n / 2 + n % 2); j++)
      if (i & (1 << j)) tmp += v[j + n / 2];
    bs.push_back(tmp);
  }
  sort(as.begin(), as.end());
  sort(bs.rbegin(), bs.rend());
  size_t ai = 0, an = as.size() - 1;
  size_t bi = 0, bn = bs.size() - 1;
  long long ans = m;
  while (ai < an || bi < an) {
    long long tmp = as[ai] + bs[bi];
    ans = min(ans, std::abs(m - tmp));
    if (tmp > m) {
      if (bi != bn)
        bi++;
      else
        ai++;
    } else {
      if (ai != bn)
        ai++;
      else
        bi++;
    }
  }
  cout << ans << endl;
  return 0;
}
