PROGRAM ATCODER

implicit none
integer(8) :: n,s,f1,f2,n_d,t1,t2,i,j,b
real(8) :: n_root

read(*,*) n,s

if(n == s)then
  write(*,'(i0)') n+1
  stop
end if

n_root = real(n)**(0.5)
n_d = int(n_root)

do i = 1, n_d
  f1 = 0 ; f2 = 0
  t1 = n ; t2 = n
  b = (n-s)/i + 1
  if(i/=1)then
    do
      f1 = f1 + mod(t1,i)
      if(t1 < i)exit
      t1 = t1/i
    end do
    if(f1 == s)then
      write(*,'(i0)') i
      stop
    end if
  end if
  do
    f2 = f2 + mod(t2,b)
    if(t2 < b)exit
    t2 = t2/b
  end do
  if(f2 == s)then
    write(*,'(i0)') b
    stop
  end if
end do

write(*,'(i0)') -1

contains
!!!!!! サブルーチンは↓

!!!!!!

END PROGRAM ATCODER
