#include <bits/stdc++.h>
using namespace std;
template <typename A, typename B>
bool cmin(A &a, const B &b) {
  return a > b ? (a = b, true) : false;
}
template <typename A, typename B>
bool cmax(A &a, const B &b) {
  return a < b ? (a = b, true) : false;
}
const double PI = acos(-1);
const double EPS = 1e-9;
long long inf = sizeof(long long) == sizeof(long long) ? 2e18 : 1e9 + 10;
int dx[] = {0, 1, 0, -1};
int dy[] = {1, 0, -1, 0};
int main() {
  long long n, m, a, b, p, q;
  cin >> n >> m >> a >> b >> p >> q;
  vector<long long> A, B;
  long long t = p;
  while (1) {
    A.push_back(t);
    if (to_string(t).size() + to_string(a).size() > 16) break;
    t *= a;
  }
  t = q;
  while (1) {
    B.push_back(t);
    if (to_string(t).size() + to_string(b).size() > 16) break;
    t *= b;
  }
  vector<long long> in;
  for (long long i = 0; i < min((long long)A.size(), n); i++)
    if (i < B.size() && A[i] + B[i] <= 3 * m) in.push_back(A[i] + B[i]);
  n = in.size() / 2;
  long long N = 1 << n;
  vector<long long> dp;
  for (long long i = 0; i < N; i++) {
    long long sum = 0;
    for (long long j = 0; j < n; j++)
      if (i & 1 << j) sum += in[j];
    if (sum <= 3 * m) dp.push_back(sum);
  }
  sort(dp.begin(), dp.end());
  long long nn = in.size() - n;
  N = 1 << nn;
  long long out = m;
  for (long long i = 0; i < N; i++) {
    long long sum = 0;
    for (long long j = 0; j < nn; j++)
      if (i & 1 << j) sum += in[n + j];
    if (sum > 3 * m) continue;
    auto it = upper_bound(dp.begin(), dp.end(), m - sum);
    if (it != dp.end()) out = min(out, abs(*it + sum - m));
    if (it == dp.begin()) continue;
    it--;
    out = min(out, abs(*it + sum - m));
  }
  cout << out << endl;
}
