#include <bits/stdc++.h>
using namespace std;
signed main() {
  long long n, m, a, b, p, q, mi;
  vector<long long> vec, num;
  cin >> n >> m >> a >> b >> p >> q;
  mi = m;
  if (a == 1 && b == 1) {
    if ((p + q) * n >= m)
      cout << min(m % (p + q), p + q - m % (p + q)) << endl;
    else
      cout << m - (p + q) * n << endl;
    return 0;
  }
  long long ta = p, tb = q;
  for (long long i = 0; i < n; i++) {
    if (ta + tb > m) break;
    vec.push_back(ta + tb);
    if (ta > (m + a - 1) / a || tb > (m + b - 1) / b) break;
    ta *= a;
    tb *= b;
  }
  n = vec.size();
  for (long long i = 0; i < (1 << (n / 2)); i++) {
    long long sum = 0;
    for (long long j = 0; j < n / 2; j++) {
      if ((i >> j) & 1) sum += vec[j];
    }
    num.push_back(sum);
  }
  sort(num.begin(), num.end());
  for (long long i = 0; i < (1 << ((n + 1) / 2)); i++) {
    long long sum = 0;
    for (long long j = 0; j < (n + 1) / 2; j++) {
      if ((i >> j) & 1) sum += vec[j + n / 2];
    }
    long long ind =
        upper_bound(num.begin(), num.end(), m - sum) - num.begin() - 1;
    if (ind >= 0) mi = min(mi, m - sum - num[ind]);
    if (ind + 1 < n) mi = min(mi, -(m - sum - num[ind + 1]));
  }
  cout << mi << endl;
  return 0;
}
