#include <bits/stdc++.h>
using namespace std;
vector<long long> generate(vector<long long> a) {
  vector<long long> ret;
  int n = a.size();
  for (int i = 0; i < (1 << n); i++) {
    long long tmp = 0;
    for (int j = 0; j < n; j++) {
      if ((1 << j) & i) tmp += a[j];
    }
    ret.push_back(tmp);
  }
  sort(ret.begin(), ret.end());
  return ret;
}
long long bs(long long m, long long sum, vector<long long> &a, bool fg) {
  int ret = -1;
  int l = 0, r = a.size() - 1;
  while (l <= r) {
    int mid = (l + r) / 2;
    long long tmp = sum + a[mid];
    if (fg) {
      if (tmp <= m) {
        ret = mid;
        l = mid + 1;
      } else {
        r = mid - 1;
      }
    } else {
      if (tmp >= m) {
        ret = mid;
        r = mid - 1;
      } else {
        l = mid + 1;
      }
    }
  }
  if (ret == -1) return llabs(m - sum);
  return llabs(m - (sum + a[ret]));
}
long long ans;
void search(int n, int now, long long sum, long long m, vector<long long> &a,
            vector<long long> &all) {
  long long ub = bs(m, sum, all, true), lb = bs(m, sum, all, false);
  ans = min(ans, ub);
  ans = min(ans, lb);
  if (now == n) return;
  search(n, now + 1, sum + a[now], m, a, all);
  search(n, now + 1, sum, m, a, all);
}
long long solve2(vector<long long> in, long long m) {
  vector<long long> mae, usiro;
  for (int i = 0; i < in.size(); i++) {
    if (i < in.size() / 2)
      mae.push_back(in[i]);
    else
      usiro.push_back(in[i]);
  }
  vector<long long> all = generate(mae);
  ans = m;
  search(usiro.size(), 0, 0, m, usiro, all);
  return ans;
}
long long solve(long long n, long long m, long long a, long long b, long long p,
                long long q) {
  if (a == 1 && b == 1) {
    long long sum = p + q;
    long long lb = min(n, m / sum), ub = min(n, (m + sum - 1) / sum);
    long long ret = m;
    ret = min(ret, llabs(m - lb * (sum)));
    ret = min(ret, llabs(m - ub * (sum)));
    return ret;
  }
  int loop = 0;
  long long cur = p + q;
  long long mula = 1, mulb = 1;
  double m_d = m;
  double cur_d = p + q;
  double mula_d = 1, mulb_d = 1;
  vector<long long> all;
  all.push_back(cur);
  while (loop < n) {
    mula_d *= a;
    mulb_d *= b;
    cur_d = p * mula_d + q * mulb_d;
    if (cur_d > 3 * m) break;
    mula *= a;
    mulb *= b;
    cur = p * mula + q * mulb;
    all.push_back(cur);
  }
  if (all.size() == 1) {
    return min(m, llabs(all[0] - m));
  }
  return solve2(all, m);
}
int main() {
  long long n, m, a, b, p, q;
  while (cin >> n >> m >> a >> b >> p >> q && n) {
    cout << solve(n, m, a, b, p, q) << endl;
  }
}
