#include <bits/stdc++.h>
using namespace std;
long long N = 0;
long long n, m, a, b, p, q;
long long calc(long long k) {
  long long A = 1, B = 1;
  while (k--) A *= a, B *= b;
  return p * A + q * B;
}
long long ans = 1LL << 60;
set<pair<long long, long long> > used;
void dfs(long long pos, long long sum) {
  if (pos >= n || pos == N + 2 || sum < 0LL) return;
  if (used.count(pair<long long, long long>(pos, sum))) return;
  used.insert(pair<long long, long long>(pos, sum));
  ans = min(ans, (long long)abs(m - sum));
  dfs(pos + 1, sum);
  long long r = calc(pos);
  if (r) dfs(pos + 1, sum + r);
}
int main() {
  cin >> n >> m >> a >> b >> p >> q;
  long long t = m, d = max(a, b);
  while (d > 1 && t) t /= d, N++;
  if (d == 1) {
    if (m / (p + q) < n)
      cout << m % (p + q) << endl;
    else
      cout << m - (p + q) * n << endl;
    return 0;
  }
  dfs(0, 0);
  cout << ans << endl;
  return 0;
}
