#include <bits/stdc++.h>
using namespace std;
long long INF = 10000000000000000LL;
long long mul(long long a, long long b) {
  if (a > INF / b) return INF;
  return a * b;
}
long long n, m, a, b, p, q;
void dfs(long long x, long long sum, vector<long long> &t,
         vector<long long> &T) {
  if (x == (int)t.size()) {
    T.push_back(sum);
  } else {
    dfs(x + 1, sum, t, T);
    dfs(x + 1, min(INF, sum + t[x]), t, T);
  }
}
long long solve() {
  if (a == 1 && b == 1) {
    long long d = p + q;
    long long total = mul(d, n);
    if (total <= m) return m - total;
    return min(m % d, m - (m % d));
  }
  vector<long long> t, u;
  long long ak = 1, bk = 1;
  for (int i = 0; i < n; i++) {
    if (i & 1)
      t.push_back(mul(ak, p) + mul(bk, q));
    else
      u.push_back(mul(ak, p) + mul(bk, q));
    ak = mul(ak, a);
    bk = mul(bk, b);
  }
  vector<long long> T, U;
  dfs(0, 0, t, T);
  dfs(0, 0, u, U);
  sort(T.begin(), T.end());
  sort(U.begin(), U.end());
  long long res = m;
  for (int i = 0; i < (int)T.size(); i++) {
    long long target = m - T[i];
    int index = lower_bound(U.begin(), U.end(), target) - U.begin();
    for (int j = index - 2; j <= index + 2; j++) {
      if (0 <= j && j < (int)U.size()) {
        res = min(res, abs(m - (T[i] + U[j])));
      }
    }
  }
  return res;
}
int main() {
  cin >> n >> m >> a >> b >> p >> q;
  cout << solve() << endl;
  return 0;
}
