#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;
long long ans;
void dfs(long long n, long long lim, long long s, long long x, long long y) {
  if (n == 0 || lim == 0) return;
  chmin(ans, abs(M - s));
  if (1.0 * x * A > 1e18) return;
  if (1.0 * y * B > 1e18) return;
  dfs(n - 1, lim - 1, s, x * A, y * B);
  dfs(n - 1, lim - 1, s + x + y, x * A, y * B);
}
signed main() {
  cin >> N >> M >> A >> B >> P >> Q;
  if (A > B) {
    swap(A, B);
    swap(P, Q);
  }
  ans = M;
  dfs(N, 26, 0, P, Q);
  if (B == 1) {
    P += Q;
    long long x = M / P * P;
    chmin(ans, abs(M - x));
    chmin(ans, abs(M - (x + P)));
  } else if (A == 1 && B == 2) {
  } else if (B == 2) {
    P += Q;
    long long x = M / P * P;
    if (N > 50 || M / P < (1ll << N)) {
      chmin(ans, abs(M - x));
    }
    if (N > 50 || M / P + 1 < (1ll << N)) {
      chmin(ans, abs(M - (x + P)));
    }
  }
  cout << ans << endl;
  return 0;
}
