#include <bits/stdc++.h>
using namespace std;
long long ticket[1000];
long long ticketSum[1000];
long long n, m, a, b, p, q;
long long cnt;
long long calc(long long depth, long long lm) {
  if (depth == cnt || lm <= 0) {
    return abs(lm);
  }
  if (ticketSum[depth] < lm) {
    return abs(lm - ticketSum[depth]);
  }
  long long ret = m;
  ret = min(ret, calc(depth + 1, lm));
  ret = min(ret, calc(depth + 1, lm - ticket[depth]));
  return ret;
}
int main() {
  cin >> n >> m >> a >> b >> p >> q;
  if (a == 1 && b == 1) {
    long long use = m / (p + q);
    use = min(use, n - 1);
    printf("%lld\n", min(m - use * (p + q), abs(m - (use + 1) * (p + q))));
    return 0;
  }
  cnt = 0;
  {
    long long left = p;
    long long right = q;
    for (long long i = 0; i < (long long)(n); ++i) {
      if (left + right > 2 * m) {
        break;
      }
      ticket[cnt++] = left + right;
      long long pleft = left;
      long long pright = right;
      left *= a;
      right *= b;
      if (left / a != pleft || right / b != pright) {
        break;
      }
    }
  }
  reverse(ticket, ticket + cnt);
  memset((ticketSum), (0), sizeof(ticketSum));
  for (long long i = cnt; i > 0; i--) {
    ticketSum[i - 1] = ticket[i - 1] + ticketSum[i];
  }
  long long ans = calc(0, m);
  printf("%lld\n", ans);
}
