#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) {
    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;
  if (x == 1) {
    cout << m - v[0] << endl;
    return 0;
  }
  set<long long> s;
  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) continue;
    s.insert(-t);
  }
  long long ans = m;
  for (long long i = 1; 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) continue;
    long long u = t - m;
    long long k = *lower_bound(s.begin(), s.end(), u);
    ans = min(ans, m - (t - k));
  }
  cout << ans << endl;
  return 0;
}
