#include <bits/stdc++.h>
using namespace std;
bool ch(long long a, long long b) {
  long long x = 1000000000000000LL;
  x /= a;
  x /= b;
  return x == 0;
}
signed main() {
  long long n, m, a, b, p, q;
  cin >> n >> m >> a >> b >> p >> q;
  if (a == 1 && b == 1) {
    if (ch(n, p + q))
      cout << m % (p + q) << endl;
    else {
      long long t = n * (p + q);
      if (m >= t)
        cout << m - t << endl;
      else
        cout << m % (p + q) << endl;
    }
    return 0;
  }
  long long ta = 1, tb = 1;
  vector<long long> v;
  for (long long i = 0; i < n; i++) {
    if (ch(p, ta)) break;
    if (ch(q, tb)) break;
    long long t = p * ta + q * tb;
    if (t <= m)
      v.push_back(t);
    else
      break;
    if (ch(ta, a)) break;
    if (ch(tb, b)) break;
    ta *= a;
    tb *= b;
  }
  long long x = v.size();
  long long y = x / 2;
  set<long long> s;
  long long ans = m;
  for (long long i = 0; i < (1 << y); i++) {
    long long t = 0;
    for (long long j = 0; j < y; j++)
      if ((i >> j) & 1) t += v[j];
    if (t > m) {
      ans = min(ans, t - m);
      continue;
    }
    s.insert(-t);
    s.insert(t);
    ans = min(ans, m - t);
  }
  long long inf = m * 2;
  s.insert(inf);
  for (long long i = 0; i < (1 << (x - y)); i++) {
    long long t = 0;
    for (long long j = 0; j < (x - y); j++)
      if ((i >> j) & 1) t += v[y + j];
    if (t > m) {
      ans = min(ans, t - m);
      continue;
    }
    ans = min(ans, m - t);
    long long u = t - m, v = m - t;
    long long k = *s.lower_bound(u);
    long long l = *s.lower_bound(v);
    ans = min(ans, m - (t - k));
    if (l != inf) ans = min(ans, (t + l) - m);
  }
  cout << ans << endl;
  return 0;
}
