#include <bits/stdc++.h>
using namespace std;
template <typename A, typename B>
inline void chmin(A &a, B b) {
  if (a > b) a = b;
}
template <typename A, typename B>
inline void chmax(A &a, B b) {
  if (a < b) a = b;
}
long long N, M, A, B, P, Q;
void dfs(long long k, long long n, long long s, vector<long long> &v,
         vector<long long> &latte) {
  if (k == n) {
    latte.push_back(s);
    return;
  }
  dfs(k + 1, n, s, v, latte);
  dfs(k + 1, n, s + v[k], v, latte);
}
signed main() {
  cin >> N >> M >> A >> B >> P >> Q;
  vector<long long> v;
  long long x = P, y = Q;
  while (true) {
    v.push_back(x + y);
    if (1.0 * x * A > 1e15 || 1.0 * y * B > 1e15) break;
    x *= A;
    y *= B;
  }
  long long n = v.size() / 2;
  vector<long long> latte, malta;
  dfs(0, n, 0, v, latte);
  dfs(n, v.size(), 0, v, malta);
  sort((latte).begin(), (latte).end());
  sort((malta).begin(), (malta).end());
  long long cur = 0;
  long long ans = M;
  for (long long i = (long long)malta.size() - 1; i >= 0; i--) {
    while (cur + 1 != latte.size() && latte[cur + 1] + malta[i] <= M) cur++;
    chmin(ans, abs(M - latte[cur] - malta[i]));
  }
  cur = 0;
  for (long long i = (long long)malta.size() - 1; i >= 0; i--) {
    while (cur + 1 != latte.size() && latte[cur] + malta[cur] < M) cur++;
    chmin(ans, abs(M - latte[cur] - malta[i]));
  }
  cout << ans << endl;
  return 0;
}
