Vanya has a scales for weighing loads and weights of masses w^0, w^1, w^2, ..., w^100 grams where w is some integer not less than 2 (exactly one weight of each nominal value). Vanya wonders whether he can weight an item with mass m using the given weights, if the weights can be put on both pans of the scales. Formally speaking, your task is to determine whether it is possible to place an item of mass m and some weights on the left pan of the scales, and some weights on the right pan of the scales so that the pans of the scales were in balance.


-----Input-----

The first line contains two integers w, m (2 ≤ w ≤ 10^9, 1 ≤ m ≤ 10^9) — the number defining the masses of the weights and the mass of the item.


-----Output-----

Print word 'YES' if the item can be weighted and 'NO' if it cannot.


-----Examples-----
Input
3 7

Output
YES

Input
100 99

Output
YES

Input
100 50

Output
NO



-----Note-----

Note to the first sample test. One pan can have an item of mass 7 and a weight of mass 3, and the second pan can have two weights of masses 9 and 1, correspondingly. Then 7 + 3 = 9 + 1.

Note to the second sample test. One pan of the scales can have an item of mass 99 and the weight of mass 1, and the second pan can have the weight of mass 100.

Note to the third sample test. It is impossible to measure the weight of the item in the manner described in the input.

Difficulty: interview

Starter code:

Solutions:
w,m=map(int,input().split())

bb=True

while(m>0 and bb):
	x=m%w
	if x==1:m-=1
	elif x==w-1:m+=1
	elif x!=0:bb=False
	m//=w
	
if bb:print("YES")
else:print("NO")

def f(w, m):
	if m == 0:
		return True
	if m % w == 0:
		return f(w, m // w)
	if (m - 1) % w == 0:
		return f(w, (m - 1) // w)
	if (m + 1) % w == 0:
		return f(w, (m + 1) // w)
	return False

w, m = map(int, input().split())
if f(w, m):
	print("YES")
else:
	print("NO")

w, m = map(int, input().split())

def isOK(w, m):
    wr = convert_base_w(m, w)
    for i in range(101):
        if wr[i] == 0 or wr[i] == 1:
            continue
        elif wr[i] == w - 1 or wr[i] == w:
            wr[i + 1] += 1
        else:
            return False
    return True

def convert_base_w(m, w):
    wr = [0] * 101
    for i in range(101):
        m, r = divmod(m, w)
        wr[i] = r
    return wr

if isOK(w, m):
    print('YES')
else:
    print('NO')

import math
import sys

def test(d):
    if d==1:
        return 1
    if d%w==0:
        k=round(d/w)
        return test(k)
    if (d-1)%w==0:
        k=round((d-1)/w)
        return test(k)
    if (d+1)%w==0:
        k=round((d+1)/w)
        return test(k)
    return 0

    


inp=list(map(int,input().split()))

w=inp[0]
m=inp[1]

a=1



for i in range(0,100):
    if a>m:
        d=a-m
        break
    a*=w
ans=test(d)
if ans==1:
    print("YES")
else:
    print("NO")


w, n = map(int, input().split(' '))
r = 1

if w <= 3:
    n = 0

while n:
    if not (n % w in {0, 1, w-1}):
        r = 0
    if n % w == w - 1:
        n = n // w + 1
    else:
        n = n // w
        
if r:
    print('YES')
else:
    print('NO')

import math

w,m=map(int,input().split())
while m>0:
	if m%w==1:
		m-=1
		m/=w
	elif m%w==w-1:
		m+=1
		m/=w
	elif m%w==0:
		m/=w
	else:
		print("NO")
		return
print("YES")

w, m = list(map(int, input().split(' ')))
f = 0
if (w == 2):
    print("YES")
else:
    st = 1
    while (f == 0):
        if (m % (st * w) != 0):
            if ((m - st) % (st * w) == 0):
                m -= st
            else:
                if ((m + st) % (st * w) == 0):
                    m += st  
                else:
                    print("NO")
                    f = 1
            if (m == 0):
                print("YES")
                f = 1                    
        st *= w


w, m = list(map(int,input().split()))

def bt(w, p, final, cur):
    if final == cur:
        return True

    if p == 0:
        return False

    if abs(cur + p - final) <= (p - 1) / (w - 1):
        if bt(w, p // w, final, cur + p):
            return True

    if abs(cur - p - final) <= (p - 1) / (w - 1):
        if bt(w, p // w, final, cur - p):
            return True

    if bt(w, p // w, final, cur):
        return True

    return False

if bt(w, w ** 35, m, 0):
    print("YES")
else:
    print("NO")


w, m = list(map(int, str.split(input())))
bits = [0] * 100
for i in range(100):

    m, bits[i] = divmod(m, w)

for i in range(99):

    if 1 < bits[i] < w - 1:

        print("NO")
        return

    if bits[i] == w - 1:

        bits[i] = 0
        bits[i + 1] += 1
        carry = 0
        for j in range(i + 1, 100):

            carry, bits[j] = divmod(bits[j] + carry, w)

print("YES")


n, m = [int(x) for x in input().split()]
balans = m
if n == 2 or m == 1:
    print('YES')
    return
cur = 1
while True:
    cur2 = cur * n
    if balans % cur2 == cur:
        balans -= cur
    elif balans % cur2 == cur2 - cur:
        balans += cur
    elif balans % cur2 == 0:
        balans += 0
    else:
        print('NO')
        return
    if balans == 0:
        print('YES')
        return
    cur = cur2

W, M = (input().split(' '))
W = int(W)
M = int(M)

if W == 2 or W == 3:
    print("YES")
else:
    N = 16
    A = [0]*(N+1)
    A[0] = 1
    for I in range(1, N):
        A[I] = A[I-1]*W
        if A[I] > 10000000001000000000:
            N = I;
            break
    #print(N)
    S = set()

    ok = False
    for msk in range(1 << N):
        curr = 0
        for I in range(N):
            if msk & (1 << I) > 0:
                curr += A[I]
        if curr == M or (curr-M in S):
            ok = True
            break
        S.add(curr)


    if ok:
        print("YES")
    else:
        print("NO")

x, y = list(map(int, input().split(' ')))

ok = []
while y % x in [0, 1, -1+x]:
    if y%x == 0:
        y //= x
        ok.append(0)
    elif y%x == 1:
        y = (y-1)//x
        ok.append(1)

    else:
        y = (y+1)//x
        ok.append(-1)

    if y == 0:
        break
        
if y == 0:
    print("YES")

else:
    print("NO")


def main():
    w, m = [int(i) for i in input().split()]
    
    if w == 2:
        print("YES")
        return
    
    s = 0
    for i in range(21):
        for sign in range(-1, 2):
            if (m - s - sign * w ** i) % w ** (i + 1) == 0:
                s += sign * w ** i
                break
    
    if abs(s) == m:
        print("YES")
    else:
        print("NO")
    
main()


n, m = list(map(int, input().split()))
a = 0
d = True
for i in range(100):
    if d and n > 0:
        if m % (n ** (a + 1)) == n ** a:
            m  -= n ** a
            a += 1
        elif m % (n ** (a + 1)) == 0:
            a += 1
        elif (m + n ** a) % (n ** (a + 1)) == 0:
            m += n ** a
            a += 1
        else:
            d = False
            print("NO")
if d:
    print("YES")


def f(m, t):
   w = 0
   nonlocal n
   while n ** w * n < m:
       w += 1
   if n ** w * n == m or (m == 1 and t != 0):
       return True
   else:
       s1 = m - n ** w
       j = False
       k = False
       if w < t:
          j = f(abs(s1), w)
       if w + 1 < t:
           k = f(abs(n ** w * n - m), w + 1)
       if k == True or j == True:
          return True
       else:
          return False
n, m = list(map(int, input().split()))
if f(m, 101):
  print('YES')
else:
  print('NO')



w,m=list(map(int,input().split()))
for u in (w**(100-i) for i in range(101)):
    m=min(m,abs(m-u))
print("YES" if m==0 else "NO")


w,m=list(map(int,input().split()))
for u in(w**(100-i)for i in range(101)):m=min(m,abs(m-u))
print("YES"if m==0 else"NO")


import math

w, m = list(map(int, input().split()))
if w == 2:
    print("YES")
else:
    n = math.ceil(math.log(1e9, w))
    for mask in range(1 << n):
        s = m
        p = 1
        for i in range(n):
            if mask & (1 << i):
                s += p
            p *= w
        while s > 0:
            if s % w > 1:
                break
            s //= w
        else:
            print("YES")
            break
    else:
        print("NO")


a, b = list(map(int, input().split(' ')))
if a == 2 or a == 3:
    print("YES")
    return

else:
    while b != 0:
        if b%a == 0:
            b //= a

        elif b%a == 1:
            b -= 1
            b //= a

        elif b%a == a-1:
            b += 1
            b //= a

        else:
            print("NO")
            return

print("YES")


w, m = list(map(int, input().split()))
arr = [0] * 103
i = 0
while m != 0:
    arr[i] = m % w
    m //= w
    i += 1
for j in range(i):
    if arr[j] == 1 or arr[j] == 0:
        pass
    elif arr[j] % w == 0:
        arr[j + 1] += 1
    elif arr[j] == w - 1:
        arr[j + 1] += 1
    else:
        print('NO')
        break
else:
    print('YES')


w,m=map(int,input().split())
for i in range(33): m=min(m,abs(w**(32-i)-m))
print("NO" if m else "YES")

#!/usr/bin/env python
# scales.py - Codeforces 552C quiz
#
# Copyright (C) 2015 Sergey
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#       http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
Vanya has a scales for weighing loads and weights of masses w0,?w1,?w2,?..
.,?w100 grams where w is some integer not less than 2 (exactly one weight
of each nominal value). Vanya wonders whether he can weight an item with mass
m using the given weights, if the weights can be put on both pans of the
scales. Formally speaking, your task is to determine whether it is possible
to place an item of mass m and some weights on the left pan of the scales,
and some weights on the right pan of the scales so that the pans of the scales
were in balance.

Input

The first line contains two integers w,?m (2<=w<=10^9, 1<=m<=10^9) - the
number defining the masses of the weights and the mass of the item.

Output

Print word 'YES' if the item can be weighted and 'NO' if it cannot.
"""

# Standard libraries
import unittest
import sys
import re

# Additional libraries


###############################################################################
# Scales Class
###############################################################################


class Scales:
    """ Scales representation """

    N = 100

    def __init__(self, args):
        """ Default constructor """

        self.args = args
        self.w = args[0]
        self.m = args[1]

        # Iterator starting position
        self.maxwp = self.calc_maxwp()
        self.it_min = 0
        self.it_max = int(3 ** (self.maxwp + 1)) - 1

        self.yes = 0

    def calc_maxwp(self):
        """ Max weight power """
        for p in range(self.N+1):
            if self.w ** p > self.m:
                return p

    def list2dec(self, it):
        result = 0
        for (n, i) in enumerate(it):
            result += i * int(3 ** n)
        return result

    def dec2list(self, dec):
        result = []
        remainder = dec
        for n in range(self.maxwp + 1):
            pow = int(3 ** (self.maxwp - n))
            div = remainder // pow
            remainder -= div * pow
            result.insert(0, div)
        return result

    def step(self):
        """ Step to the next iteration """
        mid = (self.it_max + self.it_min)//2

        if mid in (self.it_max, self.it_min):
            return 0

        w = self.calc_weight(mid)
        if w > self.m:
            self.it_max = mid
        elif w < self.m:
            self.it_min = mid
        else:
            self.yes = 1
            return 0

        return 1

    def calc_weight(self, dec):
        result = 0
        it = self.dec2list(dec)
        for i in range(len(it)):
            s = it[i]
            w = self.w ** i
            if s == 2:
                result += w
            if s == 0:
                result -= w
        return result

    def calculate(self):
        """ Main calcualtion function of the class """

        while self.step():
            pass

        return "YES" if self.yes else "NO"

###############################################################################
# Executable code
###############################################################################


def decode_inputs(inputs):
    """ Decoding input string list into base class args list """

    # Decoding input into a list of integers
    ilist = [int(i) for i in inputs[0].split()]

    return ilist


def calculate(inputs):
    """ Base class calculate method wrapper """
    return Scales(decode_inputs(inputs)).calculate()


def main():
    """ Main function. Not called by unit tests """

    # Read test input string list
    inputs = [input()]

    # Print the result
    print(calculate(inputs))

###############################################################################
# Unit Tests
###############################################################################


class unitTests(unittest.TestCase):

    def test_decode_inputs(self):
        """ Input string decoding testing """
        self.assertEqual(decode_inputs(["2 5"]), [2, 5])

    def test_Scales_class__basic_functions(self):
        """ Scales class basic functions testing """
        d = Scales([3, 7])
        self.assertEqual(d.w, 3)
        self.assertEqual(d.m, 7)

        # Find the maximum size (power) of the weight we are need
        self.assertEqual(d.maxwp, 2)

        # Base 3 Iterator value, digits: 0 - -, 1 - 0, 2 - "+"
        self.assertEqual(d.list2dec([1, 0, 2]), 19)
        self.assertEqual(d.dec2list(19), [1, 0, 2])

        # Check starting iterator
        d = Scales([2, 3])
        self.assertEqual(d.it_min, 0)
        self.assertEqual(d.it_max, 26)

        # Step function 1 - success, 0 - final step
        d = Scales([2, 3])
        self.assertEqual(d.step(), 1)
        self.assertEqual(d.it_min, 13)
        self.assertEqual(d.it_max, 26)

        # Weight from the iterator
        d = Scales([3, 7])
        self.assertEqual(d.calc_weight(d.list2dec([0, 1, 2])), 8)

    def test_calculate(self):
        """ Main calculation function """

        # Sample test 1
        self.assertEqual(calculate(["3 7"]), "YES")

        # Sample test 1
        self.assertEqual(calculate(["100 99"]), "YES")

        # Sample test 1
        self.assertEqual(calculate(["2 92600"]), "YES")

def __starting_point():
    if sys.argv[-1] == "-ut":
        unittest.main(argv=[" "])
    main()

__starting_point()

#!/usr/bin/env python
# scales.py - Codeforces 552C quiz
#
# Copyright (C) 2015 Sergey
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#       http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
Vanya has a scales for weighing loads and weights of masses w0,?w1,?w2,?..
.,?w100 grams where w is some integer not less than 2 (exactly one weight
of each nominal value). Vanya wonders whether he can weight an item with mass
m using the given weights, if the weights can be put on both pans of the
scales. Formally speaking, your task is to determine whether it is possible
to place an item of mass m and some weights on the left pan of the scales,
and some weights on the right pan of the scales so that the pans of the scales
were in balance.

Input

The first line contains two integers w,?m (2<=w<=10^9, 1<=m<=10^9) - the
number defining the masses of the weights and the mass of the item.

Output

Print word 'YES' if the item can be weighted and 'NO' if it cannot.
"""

# Standard libraries
import unittest
import sys
import re

# Additional libraries


###############################################################################
# Scales Class
###############################################################################


class Scales:
    """ Scales representation """

    N = 100

    def __init__(self, args):
        """ Default constructor """

        self.args = args
        self.w = args[0]
        self.m = args[1]

        # Iterator starting position
        self.maxwp = self.calc_maxwp()
        self.it_min = 0
        self.it_max = int(3 ** (self.maxwp + 1)) - 1

        self.yes = 0

    def calc_maxwp(self):
        """ Max weight power """
        for p in range(self.N+1):
            if self.w ** p > self.m:
                return p

    def list2dec(self, it):
        result = 0
        for (n, i) in enumerate(it):
            result += i * int(3 ** n)
        return result

    def dec2list(self, dec):
        result = []
        remainder = dec
        for n in range(self.maxwp + 1):
            pow = int(3 ** (self.maxwp - n))
            div = remainder // pow
            remainder -= div * pow
            result.insert(0, div)
        return result

    def step(self):
        """ Step to the next iteration """
        mid = (self.it_max + self.it_min)//2

        if mid in (self.it_max, self.it_min):
            return 0

        w = self.calc_weight(mid)
        if w > self.m:
            self.it_max = mid
        elif w < self.m:
            self.it_min = mid
        else:
            self.yes = 1
            return 0

        return 1

    def calc_weight(self, dec):
        result = 0
        it = self.dec2list(dec)
        for i in range(len(it)):
            s = it[i]
            w = self.w ** i
            if s == 2:
                result += w
            if s == 0:
                result -= w
        return result

    def calculate(self):
        """ Main calcualtion function of the class """

        while self.step():
            pass

        return "YES" if self.yes else "NO"

###############################################################################
# Executable code
###############################################################################


def decode_inputs(inputs):
    """ Decoding input string list into base class args list """

    # Decoding input into a list of integers
    ilist = [int(i) for i in inputs[0].split()]

    return ilist


def calculate(inputs):
    """ Base class calculate method wrapper """
    return Scales(decode_inputs(inputs)).calculate()


def main():
    """ Main function. Not called by unit tests """

    # Read test input string list
    inputs = [input()]

    # Print the result
    print(calculate(inputs))

###############################################################################
# Unit Tests
###############################################################################


class unitTests(unittest.TestCase):

    def test_decode_inputs(self):
        """ Input string decoding testing """
        self.assertEqual(decode_inputs(["2 5"]), [2, 5])

    def test_Scales_class__basic_functions(self):
        """ Scales class basic functions testing """
        d = Scales([3, 7])
        self.assertEqual(d.w, 3)
        self.assertEqual(d.m, 7)

        # Find the maximum size (power) of the weight we are need
        self.assertEqual(d.maxwp, 2)

        # Base 3 Iterator value, digits: 0 - -, 1 - 0, 2 - "+"
        self.assertEqual(d.list2dec([1, 0, 2]), 19)
        self.assertEqual(d.dec2list(19), [1, 0, 2])

        # Check starting iterator
        d = Scales([2, 3])
        self.assertEqual(d.it_min, 0)
        self.assertEqual(d.it_max, 26)

        # Step function 1 - success, 0 - final step
        d = Scales([2, 3])
        self.assertEqual(d.step(), 1)
        self.assertEqual(d.it_min, 13)
        self.assertEqual(d.it_max, 26)

        # Weight from the iterator
        d = Scales([3, 7])
        self.assertEqual(d.calc_weight(d.list2dec([0, 1, 2])), 8)

    def test_calculate(self):
        """ Main calculation function """

        # Sample test 1
        self.assertEqual(calculate(["3 7"]), "YES")

        # Sample test 1
        self.assertEqual(calculate(["100 99"]), "YES")

        # Sample test 1
        self.assertEqual(calculate(["2 92600"]), "YES")

def __starting_point():
    if sys.argv[-1] == "-ut":
        unittest.main(argv=[" "])
    main()

__starting_point()

def VI(): return list(map(int,input().split()))
def Y(): print("YES")

def run(w,m):
    if w<=3:
        Y()
        return
    mm = m
    for i in range(100):
        if m%w == 0: m //= w
        elif m%w == 1: m = (m-1)//w
        elif m%w == w-1: m = (m+1)//w
        else: break
        if m==0:
            Y()
            return
        #if w**(i) > mm: break


    print("NO")

def main(info=0):
    w,m = VI()
    run(w,m)



def __starting_point():
    main()

__starting_point()