#include <bits/stdc++.h>
using namespace std;
long long labs(long long x) {
  if (x < 0LL) return -x;
  return x;
}
int zcnt(long long x) {
  int cnt = 0;
  while (x > 0) {
    x /= 10LL;
    cnt++;
  }
  return cnt;
}
long long n, m, a, b, p, q;
long long num[51];
vector<long long> vec;
int main(void) {
  scanf("%lld%lld%lld%lld%lld%lld", &n, &m, &a, &b, &p, &q);
  if (a == 1LL && b == 1LL) {
    long long dist = p + q;
    long long cnt = m / dist;
    printf("%lld\n", min(labs(m - min(cnt, n) * dist),
                         labs(m - (min(cnt + 1LL, n)) * dist)));
  } else {
    long long v = 0;
    long long np = p, nq = q;
    while (np + nq <= m) {
      num[v] = np + nq;
      if (zcnt(np) + zcnt(a) >= zcnt(m) + 3 ||
          zcnt(nq) + zcnt(b) >= zcnt(m) + 3)
        break;
      np *= a;
      nq *= b;
      v++;
    }
    long long res = m;
    v = min(v, n);
    if (v == 0) {
      res = min(res, labs(m - p - q));
    }
    int v2 = v / 2;
    for (int bit = 0; bit < (1 << v2); bit++) {
      long long now = 0;
      for (int i = 0; i < v2; i++) {
        if ((bit >> i) & 1) {
          now += num[i];
        }
      }
      vec.push_back(now);
    }
    sort(vec.begin(), vec.end());
    vec.erase(unique(vec.begin(), vec.end()), vec.end());
    int v3 = v - v2;
    for (int bit = 0; bit < (1 << v3); bit++) {
      long long now = 0;
      for (int i = 0; i < v3; i++) {
        if ((bit >> i) & 1) {
          now += num[i + v2];
        }
      }
      int l = lower_bound(vec.begin(), vec.end(), m - now) - vec.begin();
      if (l < vec.size()) res = min(res, labs(m - now - vec[l]));
      if (l > 0 || l == vec.size()) {
        res = min(res, labs(m - now - vec[l - 1]));
      }
    }
    printf("%lld\n", res);
  }
  return 0;
}
