#include <bits/stdc++.h>
using namespace std;
const int inf = 1 << 29;
const long long INF = 1ll << 60;
const double pi = acos(-1);
const double eps = 1e-7;
const long long mod = 1e9 + 7;
const int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
long long n, m, a, b, p, q;
int main() {
  cin >> n >> m >> a >> b >> p >> q;
  vector<long long> x;
  bool B = 0;
  do {
    if (p + q > m) B = 1;
    x.push_back(p + q);
    if (INF / p > a)
      p *= a;
    else
      break;
    if (INF / q > b)
      q *= b;
    else
      break;
  } while (!B);
  int S = x.size(), S2 = S / 2, T = S - S2;
  vector<long long> c(1 << S2);
  for (int i = 0; i < 1 << S2; i++) {
    for (int j = 0; j < S2; j++)
      if (i & 1 << j) c[i] += x[j];
  }
  sort(c.begin(), c.end());
  long long res = INF;
  for (int i = 0; i < 1 << T; i++) {
    long long tmp = 0;
    for (int j = 0; j < T; j++)
      if (i & 1 << j) tmp += x[S2 + j];
    auto it = lower_bound(c.begin(), c.end(), m - tmp);
    if (it != c.end()) res = min(res, abs(m - tmp - *it));
    if (it != c.begin()) res = min(res, abs(m - tmp - *(it - 1)));
  }
  cout << res << endl;
}
