#include <bits/stdc++.h>
using namespace std;
int main() {
  long long n, m, a, b, p, q;
  cin >> n >> m >> a >> b >> p >> q;
  if (a == 1 && b == 1) {
    cout << (m / (p + q) > n ? m - (p + q) * n : m % (p + q)) << "\n";
    return 0;
  }
  double ad = 1, bd = 1;
  long long ap = 1, bp = 1;
  vector<long long> v;
  for (int i = 0; i < n; ++i) {
    if (p * ad + q * bd > 1e13 || p * ap + q * bp > m) break;
    v.push_back(p * ap + q * bp);
    ad *= a;
    bd *= b;
    ap *= a;
    bp *= b;
  }
  int l = v.size();
  int l1 = l / 2;
  int l2 = l - l1;
  set<long long> s1, s2;
  for (int i = 0; i < (1 << l1); ++i) {
    long long sum = 0;
    for (int j = 0; j < l1; ++j)
      if ((i >> j) & 1) sum += v[j];
    if (sum <= m) s1.insert(sum);
  }
  for (int i = 0; i < (1 << l2); ++i) {
    long long sum = 0;
    for (int j = 0; j < l2; ++j)
      if ((i >> j) & 1) sum += v[j + l1];
    if (sum <= m) s2.insert(sum);
  }
  long long ans = m;
  for (auto i : s1) ans = min(ans, m - i - *--s2.upper_bound(m - i));
  cout << ans << "\n";
  return 0;
}
