#include <bits/stdc++.h>
using namespace std;
long long inf = 1e17;
int main() {
  long long n, m, a, b, p, q;
  cin >> n >> m >> a >> b >> p >> q;
  if (a > b) swap(n, m), swap(a, b), swap(p, q);
  long long ans = m;
  if (b == 1) {
    long long k = p + q;
    long long d = min(n, m / k);
    ans = m - k * d;
    if (d != n) ans = min(ans, (d + 1) * k - m);
  } else if (a == 1) {
    long long bq[45] = {}, sum[46] = {};
    bq[0] = q;
    sum[1] = q;
    long long id = 0;
    for (; id < n - 1; id++) {
      if (bq[id] > inf / b) break;
      bq[id + 1] = bq[id] * b;
      sum[id + 2] = sum[id + 1] + bq[id + 1];
    }
    long long id_c = id;
    for (long long k = 1; k <= id + 1; k++) {
      if (bq[k - 1] == 0) break;
      long long left = m - p * k;
      long long now = 0;
      id = id_c;
      int use = 0;
      for (; id >= 0; id--) {
        if (now + bq[id] > left) {
          if (k - use - 1 >= 0 && k - use - 1 <= id)
            ans = min(ans, now + bq[id] + sum[k - use - 1] - left);
        } else {
          now += bq[id];
          use++;
          if (use == k) {
            ans = min(ans, left - now);
            break;
          }
        }
      }
    }
  } else {
    long long id = 0;
    long long l = p, r = q;
    long long num[40] = {};
    for (; id < n; id++) {
      num[id] = l + r;
      if (l > inf / a) break;
      if (r > inf / b) break;
      l *= a;
      r *= b;
    }
    if (id == n) id--;
    long long now = 0;
    for (; id >= 0; id--) {
      if (now + num[id] > m) {
        ans = min(ans, now + num[id] - m);
      } else {
        ans = min(ans, m - (now + num[id]));
        now += num[id];
      }
    }
  }
  cout << ans << endl;
}
