#include <bits/stdc++.h>
using namespace std;
long long n, m, a, b, p, q;
int main() {
  cin >> n >> m >> a >> b >> p >> q;
  long long res = m;
  if (a == 1 && b == 1) {
    long long cnt = min(m / (p + q), n);
    res = (res < m - cnt * (p + q) ? res : m - cnt * (p + q));
    cnt = min(cnt + 1, n);
    if (cnt * (p + q) - m >= 0)
      res = (res < cnt * (p + q) - m ? res : cnt * (p + q) - m);
    cout << res << endl;
    return 0;
  }
  long long crt1 = p, crt2 = q;
  vector<long long> cs, cs1;
  for (long long k = (long long)(0); k < (long long)(n + 1); k++) {
    if (2 * m < crt1 + crt2) break;
    cs.push_back(crt1 + crt2);
    if (2 * m / a < crt1 || 2 * m / b < crt2) break;
    crt1 *= a;
    crt2 *= b;
  }
  long long n1 = cs.size() / 2;
  long long n2 = cs.size() - n1;
  for (long long S = (long long)(0); S < (long long)(1 << n1); S++) {
    long long sum = 0;
    for (long long i = (long long)(0); i < (long long)(n1); i++) {
      if ((S >> i) & 1) sum += cs[i];
    }
    cs1.push_back(sum);
  }
  sort((cs1).begin(), (cs1).end());
  for (long long S = (long long)(0); S < (long long)(1 << n2); S++) {
    long long sum = 0;
    for (long long i = (long long)(0); i < (long long)(n2); i++) {
      if ((S >> i) & 1) sum += cs[n1 + i];
    }
    if (sum >= m) {
      res = (res < sum - m ? res : sum - m);
    } else {
      long long idx =
          lower_bound((cs1).begin(), (cs1).end(), m - sum) - cs1.begin();
      if (idx < cs1.size()) {
        res = (res < sum + cs1[idx] - m ? res : sum + cs1[idx] - m);
      }
      if (idx > 0) {
        res = (res < m - (sum + cs1[idx - 1]) ? res : m - (sum + cs1[idx - 1]));
      }
    }
  }
  cout << res << endl;
  return 0;
}
