#include <bits/stdc++.h>
using namespace std;
using VI = vector<int>;
using VVI = vector<VI>;
using PII = pair<int, int>;
using LL = __int128;
using VL = vector<LL>;
using VVL = vector<VL>;
using PLL = pair<LL, LL>;
using VS = vector<string>;
template <class S, class T>
istream& operator>>(istream& is, pair<S, T>& p) {
  return is >> p.first >> p.second;
}
template <class S, class T>
ostream& operator<<(ostream& os, const pair<S, T>& p) {
  return os << p.first << " " << p.second;
}
template <class T>
void maxi(T& x, T y) {
  if (x < y) x = y;
}
template <class T>
void mini(T& x, T y) {
  if (x > y) x = y;
}
const double EPS = 1e-10;
const double PI = acos(-1.0);
const LL MOD = 1e9 + 7;
const LL INF = 1e18;
LL abs(LL x) { return x > 0 ? x : -x; }
int main() {
  cin.tie(0);
  ios_base::sync_with_stdio(false);
  long long n_, m_, a_, b_, p_, q_;
  cin >> n_ >> m_ >> a_ >> b_ >> p_ >> q_;
  LL n, m, a, b, p, q;
  n = n_;
  m = m_;
  a = a_;
  b = b_;
  p = p_;
  q = q_;
  LL ans = INF;
  if (a == 1 && b == 1) {
    LL k = min(n, m / (p + q));
    mini(ans, abs(k * (p + q) - m));
    if (k + 1 < n) mini(ans, abs((k + 1) * (p + q) - m));
  } else {
    LL M = min((LL)42, n);
    LL M2 = M / 2;
    vector<LL> as(M + 1), bs(M + 1);
    as[0] = bs[0] = 1;
    for (int i = (0); i < (M); ++i) {
      as[i + 1] = (as[i] >= INF ? INF : as[i] * a);
      bs[i + 1] = (bs[i] >= INF ? INF : bs[i] * b);
    }
    vector<LL> xs = {0}, ys = {0};
    for (int bb = 0; bb < 1 << M2; ++bb) {
      LL sum = 0;
      for (int i = (0); i < (M2); ++i)
        if (bb >> i & 1) {
          sum += as[i] * p;
          sum += bs[i] * q;
          mini(sum, INF);
        }
      xs.push_back(sum);
    }
    for (int bb = 0; bb < 1 << (M - M2); ++bb) {
      LL sum = 0;
      for (int i = (0); i < (M - M2); ++i)
        if (bb >> i & 1) {
          sum += as[M2 + i] * p;
          sum += bs[M2 + i] * q;
          mini(sum, INF);
        }
      ys.push_back(sum);
    }
    for (auto x : xs) {
      auto it = upper_bound(begin((ys)), end((ys)), m - x);
      if (it != end(ys)) mini(ans, abs(x + *it - m));
      if (it != begin(ys)) {
        --it;
        mini(ans, abs(x + *it - m));
      }
    }
  }
  long long ans_ = ans;
  cout << ans_ << endl;
  return 0;
}
