#include <bits/stdc++.h>
using namespace std;
struct timer {
  time_t start;
  timer() { start = clock(); }
  ~timer() {
    cerr << 1. * (clock() - start) / CLOCKS_PER_SEC << " secs" << endl;
  }
};
long long n, m, a, b, p, q;
vector<long long> v;
int main() {
  cin.tie(0);
  ios_base::sync_with_stdio(0);
  cin >> n >> m >> a >> b >> p >> q;
  if (a == 1 && b == 1) {
    long long t = p + q;
    if (n < (m + t - 1) / t) {
      cout << m - t * n << endl;
    } else {
      cout << min(m % t, t - m % t) << endl;
    }
    return 0;
  }
  vector<long long> v;
  long long pa = p, qb = q;
  double pa_ = p, qb_ = q;
  for (int i = 0; i < (n); i++) {
    if (pa_ + qb_ > 3 * m) break;
    if (pa + qb > 2 * m) break;
    v.push_back(pa + qb);
    pa *= a, qb *= b;
    pa_ *= a, qb_ *= b;
  }
  vector<long long> v0, v1, sum;
  int N = ((int)(v).size()) / 2;
  for (int i = 0; i < (((int)(v).size())); i++) {
    if (i < N)
      v0.push_back(v[i]);
    else
      v1.push_back(v[i]);
  }
  for (int mask = 0; mask < (1 << ((int)(v1).size())); mask++) {
    long long s = 0;
    for (int i = 0; i < (((int)(v1).size())); i++)
      if (mask >> i & 1) {
        s += v1[i];
      }
    sum.push_back(s);
  }
  sort(sum.begin(), sum.end());
  long long ans = m;
  for (int mask = 0; mask < (1 << ((int)(v0).size())); mask++) {
    long long s = 0;
    for (int i = 0; i < (((int)(v0).size())); i++)
      if (mask >> i & 1) {
        s += v0[i];
      }
    if (s >= m) {
      ans = min(ans, s - m);
    } else {
      long long rest = m - s;
      vector<long long>::iterator it =
          lower_bound(sum.begin(), sum.end(), rest);
      ans = min(ans, *it - rest);
      it--;
      ans = min(ans, rest - *it);
    }
  }
  cout << ans << endl;
}
