#include <bits/stdc++.h>
using namespace std;
int main() {
  long long n, m, a, b, p, q;
  scanf("%lld%lld%lld%lld%lld%lld", &n, &m, &a, &b, &p, &q);
  long long ans = llabs(n * (p + q) - m);
  if (a == 1 && b == 1) {
    long long i = m / (p + q);
    for (int j = -3; j <= 3; j++)
      if (0 <= i + j && i + j <= n)
        ans = min(ans, llabs((i + j) * (p + q) - m));
  } else {
    int N;
    long long num[40];
    for (int k = 0;; k++) {
      num[k] = p * pow(a, k) + q * pow(b, k);
      if (num[k] > 1e9) {
        N = k;
        break;
      }
    }
    if (N % 2 == 1) num[N++] = 0;
    vector<long long> half1, half2;
    for (int S = 0; S < (1 << N / 2); S++) {
      bool ok1 = true, ok2 = true;
      long long sum1 = 0, sum2 = 0;
      for (int i = 0; i < (N / 2); i++)
        if (S >> i & 1) {
          sum1 += num[i];
          sum2 += num[i + N / 2];
          if (sum1 > 2e9) ok1 = false;
          if (sum2 > 2e9) ok2 = false;
        }
      if (ok1) half1.push_back(sum1);
      if (ok2) half1.push_back(sum2);
    }
    half1.push_back(0);
    half2.push_back(0);
    sort(half1.begin(), half1.end());
    sort(half2.begin(), half2.end());
    for (int i = 0; i < (half1.size()); i++) {
      int j =
          lower_bound(half2.begin(), half2.end(), m - half1[i]) - half2.begin();
      if (j < half2.size()) ans = min(ans, llabs(half1[i] + half2[j] - m));
      if (j - 1 >= 0) ans = min(ans, llabs(half1[i] + half2[j - 1] - m));
    }
  }
  printf("%lld\n", ans);
  return 0;
}
