import scala.annotation.tailrec
import scala.io.StdIn._
object Main extends App {

  val Array(a, b) = readLine.trim.split(' ').map(_.toInt)
  if (b % a != 0) {
    val g = gcd(a, b)
    val small = a / g
    val large = b / g
    val inv = (1L to small).find(_ * large % small == 1).map(i ⇒ (large - (large * i / small) % large)).get
    println((1L to small).map { i ⇒ inv * i % large * small * g }.filter{sum ⇒ sum / a < sum % b / a + sum % b % a + sum / b}.minOption.getOrElse(-1))
  }else {
    println(-1)
  }
  @tailrec def gcd(a: Long, b: Long): Long = {
    b match {
      case 0 ⇒ a
      case _ ⇒ gcd(b, a % b)
    }
  }
  implicit class Scope[T](val value: T) extends AnyVal {
    def let[A](@inline func: T ⇒ A): A = func(value)
    def also(@inline func: T ⇒ Unit): T = {func(value);value}
    def minOption[A](implicit ev: T ⇒ Iterable[A], ord: Ordering[A]): Option[A] = if (value.isEmpty) None else Some(value.min)
  }
}
