#include <bits/stdc++.h>
using namespace std;
int main() {
  long long n, m, a, b, p, q;
  cin >> n >> m >> a >> b >> p >> q;
  if (a == 1 && b == 1) {
    long long ans = m;
    long long x = p + q;
    long long y = m / x;
    if (y >= n) {
      ans = min(ans, m - x * n);
      cout << ans << endl;
    } else {
      ans = min(ans, m - (x * y));
      ans = min(ans, x - ans);
      cout << ans << endl;
    }
    return 0;
  }
  vector<long long> r1, r2;
  r1.push_back(1);
  r2.push_back(1);
  if (p + q >= m) {
    cout << min(m, p + q - m) << endl;
    return 0;
  }
  for (int i = 1; i < n; i++) {
    r1.push_back(r1[i - 1] * a);
    r2.push_back(r2[i - 1] * b);
    if (p * r1[i] + q * r2[i] >= m) {
      n = i + 1;
    }
  }
  long long ans = m;
  if (p * r1[n - 1] + q * r2[n - 1] >= m) {
    ans = min(ans, p * r1[n - 1] + q * r2[n - 1] - m);
    n--;
  }
  vector<long long> s1, s2, t1, t2;
  const long long mae = n / 2;
  const long long usi = n - mae;
  for (int i = 0; i < n / 2; i++) {
    s1.push_back(p * r1[i] + q * r2[i]);
  }
  for (int i = n / 2; i < n; i++) {
    s2.push_back(p * r1[i] + q * r2[i]);
  }
  for (long long i = 0; i < (1LL << (mae)); i++) {
    long long s = 0;
    for (long long j = 0; j < mae; j++) {
      if (i & (1LL << j)) {
        s += s1[j];
      }
    }
    t1.push_back(s);
  }
  for (long long i = 0; i < (1LL << (usi)); i++) {
    long long s = 0;
    for (long long j = 0; j < usi; j++) {
      if (i & (1LL << j)) {
        s += s2[j];
      }
    }
    t2.push_back(s);
  }
  sort(t1.begin(), t1.end());
  sort(t2.begin(), t2.end());
  for (int i = 0; i < t1.size(); i++) {
    int k = lower_bound(t2.begin(), t2.end(), m - t1[i]) - t2.begin() - 1;
    ans = min(ans, abs(m - t1[i] - t2[k]));
    if (k + 1 < usi) {
      ans = min(ans, abs(m - t1[i] - t2[k + 1]));
    }
  }
  cout << ans << endl;
  return 0;
}
