#include <bits/stdc++.h>
using namespace std;
long long int pow(long long int a, int x) {
  int ret = 1, t = x;
  while (x > 0) {
    if (x & 1) ret *= t;
    t *= t;
  }
  return ret;
}
int main() {
  long long int n, m, a, b, p, q, ans;
  cin >> n >> m >> a >> b >> p >> q;
  if (a < b) {
    swap(a, b);
    swap(p, q);
  }
  if (a == 1) {
    if (n < m / 2)
      cout << m - n * 2 << endl;
    else
      cout << m % 2 << endl;
    return 0;
  }
  ans = m;
  long long int x = 1, y = 1;
  while (p * x + q * y < m) x *= a, y *= b;
  ans = min(ans, p * x + q * y);
  while (x > 0) {
    x /= a;
    y /= b;
    ans = min(ans, abs(m - (p * x + q * y)));
    if (m > p * x + q * y) m -= p * x + q * y;
  }
  cout << ans << endl;
  return 0;
}
