#include <bits/stdc++.h>
using namespace std;
const long long INF = 1LL << 45;
long long Sum[100];
long long n, m, a, b, p, q;
long long calc(long long k) {
  long long A = 1, B = 1, res = p + q;
  while (res <= INF && k--) A *= a, B *= b, res = p * A + q * B;
  return min(INF, res);
}
long long ans = INF;
set<long long> used[101];
void dfs(long long pos, long long sum) {
  ans = min(ans, (long long)abs(m - sum));
  if (m < sum || pos == -1 || sum > INF || used[pos].count(sum)) return;
  if (Sum[pos] + sum < m) {
    ans = min(ans, m - (Sum[pos] + sum));
    return;
  }
  used[pos].insert(sum);
  dfs(pos - 1, sum + calc(pos));
  dfs(pos - 1, sum);
}
int main() {
  cin >> n >> m >> a >> b >> p >> q;
  Sum[0] = calc(0);
  for (int i = 1; i < 60; i++) Sum[i] = min(INF, calc(i) + Sum[i - 1]);
  if (max(a, b) == 1) {
    long long s = abs(m - (m / (p + q)) * (p + q));
    long long t = abs(m - (m / (p + q)) * (p + q) - (p + q));
    if (m / (p + q) == n) t = INF;
    if (m / (p + q) <= n)
      cout << min(s, t) << endl;
    else
      cout << m - (p + q) * n << endl;
    return 0;
  }
  dfs(min(n - 1, 50LL), 0);
  cout << ans << endl;
  return 0;
}
