#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 == b && b == 1) {
    if (m >= (p + q) * n)
      cout << min(m % (p + q), ((p + q) - (m % (p + q))) % (p + q)) << endl;
    else
      cout << m - (p + q) * n << endl;
    return 0;
  }
  vector<long long> nums;
  __int128_t pa = p, qb = q;
  for (long long i = 0; i < (long long)(n); i++) {
    if (pa + qb >= 2 * m) break;
    nums.push_back(pa + qb);
    pa *= a;
    qb *= b;
  }
  int l = nums.size();
  int s1 = l / 2, s2 = l - s1;
  ;
  vector<long long> lsr(begin(nums), begin(nums) + s1);
  vector<long long> gtr(begin(nums) + s1, end(nums));
  vector<long long> l1(1 << s1), l2(1 << s2);
  for (long long i = 0; i < (long long)(1 << s1); i++)
    for (long long j = 0; j < (long long)(s1); j++)
      if ((i >> j) & 1) l1[i] += lsr[j];
  for (long long i = 0; i < (long long)(1 << s2); i++)
    for (long long j = 0; j < (long long)(s2); j++)
      if ((i >> j) & 1) l2[i] += gtr[j];
  sort(begin(l2), end(l2));
  long long mn = m;
  for (long long i = 0; i < (long long)(1 << s1); i++) {
    auto itr = lower_bound(begin(l2), end(l2), m - l1[i]);
    if (itr != end(l2)) mn = min(mn, (l1[i] + *itr) - m);
    if (itr != begin(l2)) mn = min(mn, m - (l1[i] + *prev(itr)));
  }
  cout << mn << endl;
  return 0;
}
