#include <bits/stdc++.h>
using namespace std;
long long n, m, a, b, p, q, ans;
long long d[45], used[45];
int main() {
  cin >> n >> m >> a >> b >> p >> q;
  ans = m;
  if (a == 1 && b == 1) {
    long long ti = min(n, m / (p + q));
    ans =
        min(ans, min(abs(m - ti * (p + q)), abs(m - min(ti + 1, n) * (p + q))));
  }
  long long A = 1, B = 1;
  for (int i = 0; i < min((long long)45, n); i++) {
    d[i] = p * A + q * B;
    if (d[i] > m) break;
    A *= a, B *= b;
  }
  for (int i = min((long long)45, n) - 1; i >= 0; i--) {
    if (m < d[i]) continue;
    used[i] = 1;
    m -= d[i];
  }
  ans = min(ans, m);
  for (int i = 0; i < min((long long)45, n) - 1; i++)
    if (!used[i]) {
      ans = min(ans, abs(m - d[i]));
      break;
    }
  cout << ans << endl;
  return 0;
}
