object main extends App with fastIO {

  var Array(a, b, s) = readLine split(" ") map(_.toInt)
  println(if (((s - a.abs - b.abs) & 1) == 0 && s >= a.abs + b.abs) "Yes" else "No")

  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken
    in.sval
  }

  def nextInt: Int = {
    in.nextToken
    in.nval.toInt
  }

  def nextLong:Long ={
    in.nextToken
    in.nval.toLong
  }

  def nextDouble: Double = {
    in.nextToken
    in.nval.toDouble
  }

  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush = out.flush
}


object P8B {
    import io.StdIn._

    def main(args:Array[String]) {
        val m = collection.mutable.HashMap[(Int, Int), Int]()
        val s = readLine
        var k = 0
        def f(i:Int, x:Int, y:Int) {
            if (!m.contains((x, y))) {
                m((x, y)) = k
                k += 1
            }
            if (i < s.size) s(i) match {
                case 'L' => f(i + 1, x, y - 1)
                case 'R' => f(i + 1, x, y + 1)
                case 'U' => f(i + 1, x - 1, y)
                case 'D' => f(i + 1, x + 1, y)
            }
        }; f(0, 0, 0)
        val e = Array.fill(k){collection.mutable.Buffer[Int]()}
        for (((x, y), i) <- m) {
            for (xyN <- Array((x + 1, y), (x, y + 1))) m.get(xyN) match {
                case Some(j) => {e(i).+=(j); e(j).+=(i)}
                case None => {}
            }
        }
        val d = Array.fill(k){Int.MaxValue}; d(0) = 0
        val q = collection.mutable.Queue[Int](0)
        while (q.nonEmpty) {
            val qH = q.dequeue
            for (i <- e(qH)) if (d(i) > d(qH) + 1) {
                d(i) = d(qH) + 1
                q.enqueue(i)
            }
        }
        println(if (d(k - 1) == s.size) "OK" else "BUG")
    }
}


object CF499B extends App {

  import java.io.PrintWriter
  import java.util.Scanner

  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def solve = {
    val participants = in.nextInt
    val food = new Array[Int](in.nextInt).map(_ => in.nextInt).groupBy(identity).mapValues(_.size).map(_._2).toArray.sorted.reverse

    def tryNDays(days: Int): Boolean = {
      if (days == 0) return true
      return food.map(_/days).sum >= participants
    }

    out.println(Stream.from(0).takeWhile(tryNDays).last)
  }

  solve
  out.flush
  out.close
}


object Main {

  def main(args: Array[String]) {

    val std = scala.io.StdIn
    val n = std.readLine().toInt

    var divisors = std.readLine().split(" ").map(_.toInt).sorted.reverse.toList
    val first = divisors.head

    divisors = divisors.tail
    var prev = first
    while (divisors.length > 1 && divisors.head != prev && first % divisors.head == 0 ) {
      prev = divisors.head
      divisors = divisors.tail
    }

    println(divisors.head + " " + first)

  }
}


import java.util.Scanner

/**
 * Created by hama_du on 2014/03/12.
 */
object ProblemC extends App {
  val in = new Scanner(System.in)
  val recipe = in.next.toCharArray
  val B = recipe.count(p => p == 'B')
  val S = recipe.count(p => p == 'S')
  val C = recipe.count(p => p == 'C')
  val b,s,c = in.nextLong
  val pb,ps,pc = in.nextLong
  val P = in.nextLong

  println(binSearch(-1, 1000000000000000L))

  def binSearch(min: Long, max:Long): Long = {
    if (max - min <= 1) {
      min
    } else {
      val med = (min + max) / 2
      if (isPossible(med)) {
        binSearch(med, max)
      } else {
        binSearch(min, med)
      }
    }
  }

  def isPossible(med: Long): Boolean = {
    val needB = (med * B - b) max 0
    val needS = (med * S - s) max 0
    val needC = (med * C - c) max 0
    (needB * pb + needS * ps + needC * pc) <= P
  }
}


import scala.collection.mutable.ArraySeq

object Main {

  def main(args: Array[String]) {
    val Array(n, l, r) = scala.io.StdIn.readLine split ' ' filter (_.nonEmpty) map (_.toInt)
    val numDiv3 = (l: Int, r: Int) => r / 3 - (l + 2) / 3 + 1
    val (a, b, c) = (numDiv3(l, r), numDiv3(l - 1, r - 1), numDiv3(l + 1, r + 1))
    println((Matrix(ArraySeq(ArraySeq(a, c, b), ArraySeq(b, a, c), ArraySeq(c, b, a))) ** n) (0)(0))
  }

  val MOD = 1000000007

  class Matrix(val n: Int, val m: Int, val mat: ArraySeq[ArraySeq[Long]]) {
    def apply(i: Int) = mat(i)
    def *(oth: Matrix) = {
      val res = Matrix(n, oth.m)
      for (i <- 0 until n; k <- 0 until m; j <- 0 until oth.m) {
        res(i)(j) = (res(i)(j) + mat(i)(k) * oth.mat(k)(j)) % MOD
      }
      res
    }
    def **(k: Int): Matrix =
      if (k == 1)
        this
      else {
        val hf = this ** (k / 2)
        val res = hf * hf
        if (k % 2 == 0) res
        else res * this
      }
  }

  object Matrix {
    def apply(mat: ArraySeq[ArraySeq[Long]]) = new Matrix(mat.length, mat(0).length, mat)
    def apply(n: Int, m: Int) = new Matrix(n, m, ArraySeq.fill(n, m)(0))
  }
}


object Main
{
  def main(args : Array[String]) = {
    val Array(n,a,b,c) = readLine.split(" ").map(_.toInt)
    var res = 0
    for (i <- 0 to n/a; j <- 0 to n/b)
    {
      val r = n-i*a-j*b
      if (r>=0 && r % c == 0)
	res = res max (i + j + r/c)
    }
    println(res)
  }
}


import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, java.awt._

object _669A extends CodeForcesApp {
  override def apply(io: IO) = {
    val n = io[Int]
    val ans = 2*(n/3) + (if (n%3 > 0) 1 else 0)
    io += ans
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = t.head.ensuring(t.size == 1)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount: Int = java.lang.Long.bitCount(x)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def  asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])
  }
  def memoize[I] = new {
    def apply[O](f: I => O): I => O = new mutable.HashMap[I, O]() {
      override def apply(key: I) = getOrElseUpdate(key, f(key))
    }
  }
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  val mod: Int = (1e9 + 7).toInt
  val newLine: String = "\n"
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

class IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    if (tokenizers.nonEmpty) Some(tokenizers.head) else None
  }

  def apply[A](implicit read: IO.Read[A]): A = read.apply(this)
  def apply[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(apply).to[C]

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine(): String = till("\n\r")

  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty

  var separator = " "
  private[this] var isNewLine = true

  def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {
    write(this)(x)
    this
  }
  def ++=[A: IO.Write](xs: Traversable[A]): this.type = this.+=(xs.size).appendNewLine().+=(xs)

  def appendNewLine(): this.type = {
    println()
    this
  }

  override def print(obj: String) = {
    if (isNewLine) isNewLine = false else super.print(separator)
    super.print(obj)
  }
  override def println() = if (!isNewLine) {
    super.println()
    isNewLine = true
  }
  override def close() = {
    flush()
    in.close()
    super.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r[C, A](r[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val boolean                                      : Read[Boolean]      = string.map(_.toBoolean)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r[A], r[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r[A], r[B], r[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))
  }
  trait Write[-A] {
    def apply(out: PrintWriter)(x: A): Unit
  }
  trait DefaultWrite {
    implicit def any[A]: Write[A] = Write(_.toString)
  }
  object Write extends DefaultWrite {
    def apply[A](f: A => String) = new Write[A] {
      override def apply(out: PrintWriter)(x: A) = out.print(f(x))
    }
    implicit val boolean: Write[Boolean] = Write(b => if (b) "YES" else "NO")
    implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s"$a $b"}
    implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {
      override def apply(out: PrintWriter)(xs: Traversable[A]) = {
        xs foreach write(out)
        out.println()
      }
    }
  }
}


import java.io.PrintWriter
import java.util.Scanner

/**
 * Created by arseny on 19.07.14.
 */
object C extends App {
  val home = true
  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def nextInt = in.nextInt
  def nextLong = in.nextLong
  def nextDouble = in.nextDouble
  def nextString = in.next

  def solve() = {
    val n = nextLong
    val m = nextLong
    val k = nextLong
    if (k > n + m - 2) {
      out.println(-1)
    } else {
      def minSquare(t: Long) = {
        (n / (t + 1)) * (m / (k - t + 1))
      }
      val l = math.max(0, k - m + 1)
      val r = math.min(k, n - 1)
      var max = l
      if (minSquare(r) > minSquare(max)) {
        max = r
      }
      if (r != 0 && minSquare(r - 1) > minSquare(max)) {
        max = r - 1
      }
      if (l != k && minSquare(l + 1) > minSquare(max)) {
        max = l + 1
      }
      out.println(minSquare(max))
    }
  }

  try {
    solve()
  } catch {
    case _: Exception => sys.exit(9999)
  } finally {
    out.flush()
    out.close()
  }
}


/**
  * Created by octavian on 13/02/2016.
  */
object Cards {

  def main(args: Array[String]) = {

    //System.setIn(new FileInputStream("./src/cards.in"))
    //System.setOut(new PrintStream(new FileOutputStream("./src/cards.out")))

    val n = readInt()
    val a: Array[Char] = readLine().toCharArray
    var count = Array(0, 0, 0)
    var chars = Array('B', 'R', 'G')
    for(i <- 0 until a.length) {

      a(i) match {
        case 'B' => count(0) += 1
        case 'R' => count(1) += 1
        case 'G' => count(2) += 1
      }
    }

    println(computePos(count, chars).sorted.mkString)
  }

  def computePos(count: Array[Int], chars: Array[Char]): Array[Char] = {
    for(i <- 0 until 3) {
      for(j <- 0 until 3) {
        for(k <- 0 until 3) {
          if(i != j && i != k && j != k) {
            if(count(i) > 0 && count(j) == 0 && count(k) == 0) {
              //println("In 1: " + i + " " + j + " " + k)
              return Array(chars(i))
            }
            if(count(i) == 1 && count(j) == 1 && count(k) == 0) {
              //println("In 1: " + i + " " + j + " " + k)
              return Array(chars(k))
            }
            if(count(i) > 1 && count(j) == 1 && count(k) == 0) {
              //println("In 1: " + i + " " + j + " " + k)
              return Array(chars(j), chars(k))
            }
          }
        }
      }
    }
    return chars
  }

}


object Main {
  def main(args: Array[String]) {
    val Array(a, b) = readLine().split(" ").map(_.toInt)

    var rest = a
    var sum = a
    while(rest >= b) {
      sum += rest / b
      rest = rest / b + rest % b
    }
    println(sum)
  }
}


import scala.io._
import scala.collection.mutable._
import java.util.StringTokenizer

object HelloWorld {

  def main(args: Array[String]): Unit = {
    var Array(l, d, v, g, r) = readLine.split(" ").map(_.toDouble);
    var result: Double = 0;
    var timeToTraffic = d / v;
    var mod = timeToTraffic % (g + r);
    var green = if (mod >= 0 && mod < g) true else false
    if (green) {
      result = l / v;
    } else {
      result = d / v + (r - (mod - g)) + (l - d) / v;
    }
    println(result);
  }

}


import java.util.Scanner

object Main {

  def sqr(x: Long) = x * x

  def powmod(x: Long, n: Long, p: Long): Long = {
    if (n == 1) x
    else if (n % 2 == 1) (powmod(x, n - 1, p) * x) % p
    else sqr(powmod(x, n / 2, p)) % p
  }

  def C(n: Int, k: Int) = {
    var res = BigInt(1)
    for (i <- n - k + 1 to n) {
      res = res * i
    }
    for (i <- 1 to k.toInt) {
      res = res / i
    }
    res
  }

  def fact(n: Int) = {
    var res = BigInt(1)
    for (i <- 1 to n) {
      res = res * i
    }
    res
  }

  def gcd(a: Long, b: Long): Long = if (b == 0) a else gcd(b, a % b)

  def lcm(a: Long, b: Long) = a / gcd(a, b) * b

  def main(args: Array[String]): Unit = {
    val in = new Scanner(System.in)

    val primes = Array(2, 3, 5, 7)

    val R = in.nextLong()

    var res = 0L

    for (mask <- 0 until (1 << primes.length)) {
      var prod = 1L
      var cnt = 0
      for (i <- primes.indices) {
        if ((mask & (1 << i)) != 0) {
          prod = prod * primes(i)
          cnt = cnt + 1
        }
      }
      //System.err.println(prod)
      res = res + (if (cnt % 2 == 0) 1 else -1) * (R / prod)
    }

    println(res)

  }
}


import java.util.Scanner

object Main {

	def main(args: Array[String]): Unit = {
		val scanner = new Scanner (System.in)
		val s = scanner.next ()
		val t = s.sorted.reverse
		val ans = t.takeWhile(c => c == t.head)
		println (ans)
	}

}


object Main {
  def main(args: Array[String]) {
    val op = readLine().split(" ").map(_.toInt)
    val a = readLine().split(" ").map(_.toInt)
    val n = op(0)
    val m = op(1)
    val k = op(2)

    val r = a.sorted.reverse.scanLeft(k)(_ + _ - 1)
    val count = if(m < k) 0 else r.zipWithIndex.find(_._1 >= m).map(_._2).getOrElse(-1)
    println(count)
  }
}


import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

object A_425 {   var br = createBufferedReader(); var debugV = false

    //COMMENT ME !
    runTest(Test.sa1)
    debugV = true
//    file = File("C:\\temp\\google cj\\2014q\\c-small.res")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val l1 = readLine
    val n = l1.long
    val k = l1.long

    val rr = n / k
    val res = if (rr % 2 == 1) "YES" else "NO"

    //---------------------------- parameters reading :end
    outLn(res)
    finish
  }

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Integer) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

  def readLine() = new Line
  class Line {
    val fullLine = br.readLine()
    val tok = new StringTokenizer(fullLine, " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

//============================================================================================
object Test {

val sa1 = """
10 4
"""

val sa2 = """
1 1
"""

val sa3 = """
"""
}

}


object _937A extends CodeForcesApp {
  import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._

  override def apply(io: IO): io.type = {
    val input = io.read[Vector[Int]]
    val ans = input.filter(_ > 0).distinct.size
    io.write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  type Point = java.awt.geom.Point2D.Double
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int = 0, until: Int = a.length)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int = 0, until: Int = a.length)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p._1, ev(p._2))
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
    def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    //def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def getBit(i: Int): Int = (x >> i) & 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def getBit(i: Int): Long = (x >> i) & 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative.getOrElse(f)   //e.g. students.indexOf("Greg").whenNegative(Int.MaxValue)
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new Point(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
  val printer = new PrintWriter(out, true)

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    when(tokenizers.nonEmpty)(tokenizers.head)
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                      : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}


import java.util.Scanner

object DashaAndFriends extends App {
  def parseInts(str: String, numIterations: Integer) = {
    val scanner = new Scanner(str)
    val res = (0 until numIterations) map (_ => scanner.nextInt())
    scanner.close()
    res
  }

  val trackInfo = parseInts(Console.readLine(), 2);

  val numObstacles = trackInfo(0)

  val trackLen = trackInfo(1)

  val kefaStats = parseInts(Console.readLine(), numObstacles)

  val sashaStats = parseInts(Console.readLine(), numObstacles)

  def tailRecurse(stats1: Seq[Int], stats2: Seq[Int], tail1: Int, trackLen: Int, distToNextNode1: Int, distToNextNode2: Int, jumps: Int): Int = {
    val statLen = stats1.size
    if (jumps >= statLen || distToNextNode1 != distToNextNode2) statLen - jumps
    else {
      val head1 = tail1 + jumps
      val nextNode = stats1((head1) % statLen)
      val thisNode = (if ((head1) % statLen != 0) stats1((head1 - 1) % statLen) else stats1((head1 - 1) % statLen) - trackLen)
      tailRecurse(
        stats1,
        stats2,
        tail1,
        trackLen,
        distToNextNode1 + nextNode - thisNode,
        distToNextNode2 + stats2(jumps) - stats2(jumps - 1),
        jumps + 1)
    }
  }

  def checkRotation(stats1: Seq[Int], stats2: Seq[Int], tail1: Int, tail2: Int, distToNextNode1: Int, distToNextNode2: Int, counter: Int): String = {
    val statLen = stats1.size
    // TODO mdaniel Remove the counter and replace with better solution for tail
    if (counter >= statLen) "NO" // should this be statlen - 1???
    else {
      // TODO mdaniel Improve the logic for passing in tail1 to be for current tail. Now it's more like next tail
      val allEqualDistance = tailRecurse(stats1, stats2, (tail1 + 1) % statLen, trackLen, distToNextNode1, distToNextNode2, 1)
      if (allEqualDistance == 0) "YES"
      else {
        val newTail1 = (tail1 + 1) % statLen
        checkRotation(stats1, stats2, newTail1, tail2,
          stats1((newTail1 + 1) % statLen) - stats1(newTail1),
          distToNextNode2, counter + 1
        )
      }
    }
  }

  def isSameTrack(stats1: Seq[Int], stats2: Seq[Int], trackLen: Int): String = {
    val statLen = stats1.size

    val start = statLen - 1

    val distToNextNode1 = trackLen - stats1(start) + stats1(0)
    val distToNextNode2 = trackLen - stats2(start) + stats2(0)

    checkRotation(stats1, stats2, start, start, distToNextNode1, distToNextNode2, 0)

//    (0 until statLen).filter(x => tailRecurse(stats1, stats2, i, trackLen, distToNextNode1, distToNextNode2, 1) == 0)
//    for (i <- 0 until statLen) {
//      val allEqualDistance = tailRecurse(stats1, stats2, i, trackLen, distToNextNode1, distToNextNode2, 1)
//
//      if (allEqualDistance == 0) {
//        return "YES"
//      }
//
//      // update head1
//      head1 = (head1 + 1) % statLen
//      distToNextNode1 = stats1((i + 1) % statLen) - stats1(head1)
//      // Start this one at a constant spot
//      distToNextNode2 = trackLen - stats2(head2) + stats2(0)
//    }
//
//    "NO"
  }

  println(isSameTrack(kefaStats, sashaStats, trackLen))
}


object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val sq = Math.sqrt(n).ceil.toInt
    val a = for {
      i <- 1 to sq
      j <- i + 1 to sq
      k <- 1 to n / (i * i + j * j)
      a = k * (j * j - i * i)
      b = k * 2 * i * j
      c = k * (i * i + j * j)
      if a <= n
      if b <= n
      if c <= n
    } yield(a.min(b), a.max(b), c)
    println(a.toSet.size)
  }
}


object A373 {

  import IO._
  import collection.{mutable => cu}

  def main(args: Array[String]): Unit = {
    val Array(k) = readInts(1)
    val in = Array.fill(4)(read)
      .flatMap(_.toCharArray.filter(_!='.').map(_-'0'))
      .groupBy(identity)
      .mapValues(_.length)
      .values
    if(in.exists(_ > 2*k))
      println("NO")
    else
      println("YES")
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    @inline def read: String = input.readLine()

    @inline def tokenizeLine = new java.util.StringTokenizer(read)

    def readInt: Int = tokenizeLine.nextToken.toInt

    def readInts(n: Int): Array[Int] = {
      val tl = tokenizeLine
      Array.fill(n)(tl.nextToken.toInt)
    }

    def readLongs(n: Int): Array[Long] = {
      val tl = tokenizeLine
      Array.fill(n)(tl.nextToken.toLong)
    }

    def readBigs(n: Int): Array[BigInt] = {
      val tl = tokenizeLine
      Array.fill(n)(BigInt(tl.nextToken))
    }
  }

}


/**
  * @author ShankarShastri
  *         Algorithm: ProblemA(http://codeforces.com/contest/999/problem/A)
  */

import scala.io.StdIn._

object ProblemA {
  def solveContestForMiska(list: List[Int], k: Int) = {
    val leftList =  list.takeWhile(_ <= k)
    leftList.length + list.splitAt(leftList.length)._2.reverse.takeWhile(_ <= k).length
  }
  def readLineToList[Int]() = readLine.split(" ").map(_.toInt).toList
  def main(args: Array[String]): Unit = {
   val Array(n,k) = readLine.split(" ").map(_.toInt)
    val list = readLineToList()
    println(solveContestForMiska(list, k))
  }
}


object Solution133A extends App {

  def solution() {
    val s = _string
    if (s.contains("H") || s.contains("Q") || s.contains("9")) {
      println("YES")
    } else {
      println("NO")
    }
  }

  //////////////////////////////////////////////////
  import java.util.Scanner
  val SC: Scanner = new Scanner(System.in)
  def _line: String = SC.nextLine
  def _int: Int = SC.nextInt
  def _long: Long = SC.nextLong
  def _string: String = SC.next
  solution()
}


object Main {
  def main(args: Array[String]) = {
    val a1 = readLine().split(" ").map(_.toInt)
    val a2 = readLine().split(" ").map(_.toInt)
    val a3 = readLine().split(" ").map(_.toInt)

    val sum = a1.sum + a2.sum + a3.sum
    a1(0) = sum / 2 - a1.sum
    a2(1) = sum / 2 - a2.sum
    a3(2) = sum / 2 - a3.sum
    println(a1.mkString(" "))
    println(a2.mkString(" "))
    println(a3.mkString(" "))
  }
}


object Main extends App{
  val in= readLine
  val Array(d1, d2, d3)=in.split(' ').map(_.toInt)
  println(Math.min(Math.min(Math.min(d1 + d2, d1 + d3), d2 + d3)*2, d1 + d2 + d3))}


// http://codeforces.com/contest/394/problem/A
object A extends App {
  val in = readLine()
  val lr = in.split('=')
  val ls = lr(0).split('+')
  val ca = ls(0).count(_ == '|')
  val cb = ls(1).count(_ == '|')
  val cc = lr(1).count(_ == '|')
  val l = ca + cb
  val r = cc
  if (l == r) println(in)
  else if (l-r == 2) {
    if (ca>1) println("|"*(ca-1)+"+"+"|"*cb+"="+"|"*(cc+1))
    else  println("|"*ca+"+"+"|"*(cb-1)+"="+"|"*(cc+1))
  }
  else if (r-l == 2) {
    if (cc == 1) println("Impossible")
    else println("|"*(ca+1)+"+"+"|"*cb+"="+"|"*(cc-1))
  }
  else println("Impossible")
}


object B268 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

  def readInts(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)
  }

  def readLongs(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)
  }

  def readBigs(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))
  }

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    var res = n.toLong
    for(i <- n-1 to 1 by -1) {
      res += (n-i)*i
    }
    println(res)
  }
}


object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val Array(n, a, b) = in.next().split(" ").map(_.toInt)
  println(n - Math.max(a, n - b - 1))
}


import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = {
    val is = new Scanner(System.in)
    val n = is.nextInt()

    var t = 0
    var i = 1
    while (t + i <= n) {
      t += i
      i += 1
    }

    i -= 1
    println(i)
    val res = (1 to i).updated(i - 1, i + n - t).mkString(" ")
    println(res)
  }
}


object E extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }

  val Array(n) = readInts(1)
  val as = readInts(n)
  val sum = as.sum
  var dp = Array.fill(1, sum + 1)(0L)
  var maxSum = as.max

  for (i <- 0 until n) {

    val dp2 = Array.ofDim[Array[Long]](i + 2)
    var dd = 0
    while (dd < dp.length) {
      dp2(dd) = dp(dd).clone()
      dd += 1
    }
    dp2(dd) = Array.fill(sum + 1)(0L)

    val a = as(i)
    var j = 1
    val maxSumCurrent = maxSum
    while (j <= i) {
      var s = 0
      while (s <= maxSumCurrent) {
        if (dp(j)(s) > 0) {
          dp2(j + 1)(s + a) = dp2(j + 1)(s + a) + dp(j)(s)
          if (s + a > maxSum) maxSum = s + a
        }
        s += 1
      }
      j += 1
    }
    dp2(1)(a) += 1
    dp = dp2
  }

  val counted = as.groupBy(identity).map {
    case (a, x) => a -> x.length
  }

  val pascal = Array.ofDim[Long](n + 1, n + 1)
  for (i <- pascal.indices) pascal(i)(0) = 1L
  for (i <- 1 until pascal.length) {
    var j = 1
    while (j < pascal(i).length) {
      pascal(i)(j) = pascal(i - 1)(j - 1) + pascal(i - 1)(j)
      j += 1
    }
  }

  var res = 1
  if (counted.size == 2) {
    res = n
  } else {
    for ((a, count) <- counted) {
      for (i <- 1 to count) {
        if ((dp(i)(a * i) == pascal(count)(i) ||
          dp(n - i)(sum - a * i) == 1)
          && i > res) {
          res = i
        }
      }
    }
  }

  println(res)
}


//package merofeev.contests.codeforces.rnd372

import java.util.Scanner

/**
  * @author erofeev
  * @since 17.09.16
  */
object BAlphabet {

  def main(args: Array[String]): Unit = {
    val str = new Scanner(System.in).nextLine
    if (str.length < 26) {
      println(-1)
      return
    }

    val chars = new Array[Int](26)
    var counter = 0

    for (pos <- 0 until str.length) {
      if (str(pos) == '?') {
        counter += 1
      } else {
        chars(str(pos) - 'A') += 1
        if (chars(str(pos) - 'A') == 1) {
          counter += 1
        }
      }
      if (pos > 25) {
        if (str(pos - 26) == '?') {
          counter -= 1
        } else {
          chars(str(pos - 26) - 'A') -= 1
          if (chars(str(pos - 26) - 'A') == 0) {
            counter -= 1
          }
        }
      }
      if (counter == 26) {
        val preres: String = str.substring(pos - 25, pos + 1)
        val sb = buildRes(str, chars, preres)
        val left: String = str.substring(0, pos - 25).replaceAll("\\?", "A")
        val right: String = str.substring(pos + 1).replaceAll("\\?", "A")
        println(left + sb + right)
        return
      }
    }
    println(-1)
  }

  def buildRes(str: String, chars: Array[Int], preres: String): String = {
    val sb = new StringBuilder(preres)
    var curr = 0
    while (chars.length > curr && chars(curr) > 0) curr += 1
    for (elem <- 0 until 26) {
      if (sb(elem) == '?') {
        sb.setCharAt(elem, ('A' + curr).toChar)
        curr += 1
        while (chars.length > curr && chars(curr) > 0) {
          curr += 1
        }
      }
    }
    sb.toString()
  }
}


object Main {
  def gcd(a: Int, b: Int): Int =
    if (a % b == 0) b
    else gcd(b, a % b)

  def lcd(a: Int, b: Int): Int = (a.toLong * b.toLong / gcd(a, b)).toInt

  def main(args: Array[String]) {
    val xyab = readLine().split(" ").map(_.toInt)
    val x = xyab(0)
    val y = xyab(1)
    val a = xyab(2)
    val b = xyab(3)
    val lcd0 = lcd(x, y)
    val upper = b / lcd0
    val lower = (a + lcd0 - 1) / lcd0
    val count = upper - lower + 1
    println(count)
  }
}


import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._
import CodeForcesApp._
object _588B extends CodeForcesApp[Long]({scanner => import scanner._
  val n = nextLong
  val divisors = bag[Long]

  for {
    i <- 1 to Math.sqrt(n.toDouble).ceil.toInt if n%i == 0
  } {
    divisors += i.toLong
    divisors += n/i
  }
  val squares = divisors.map(i => i*i)
  val lovely = divisors.filterNot(x => squares.exists(s => s > 1 && x%s == 0))
  //debug(lovely)
  lovely.max
}) {
  override def format(result: Result) = super.format(result)
}
/********************************************************************************************/
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final type Result = A
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: Result): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val mod: Int = 1000000007
  final val eps: Double = 1e-9
  @inline final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  @inline final def repeat[A](n: Int)(f: => A): Seq[A] = (1 to n).map(_ => f)
  @inline final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse
  import scala.collection.mutable.{Map => Dict, Set => Bag}
  final def nil[A]: List[A] = List.empty[A]
  final def bag[A]: Bag[A] = Bag.empty[A]
  final def map[A] = new {
    def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default
  }
}


import scala.annotation.tailrec
import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn._

object C extends App {
  val Max = 8e15.toLong + 1

  val m = readLong()

  def count(n: Long): Long = {
//    print(s"count($n)=")
    var result = 0L
    var k = 2L
    while (k * k * k <= n) {
      result += n / (k.toLong * k * k)
      k += 1
    }

//    println(result)
    result
  }

  var left = 0L
  var right = Max

  def find: Long = {
    while (left < right) {
      val mid = (left + right) / 2L
//      println(s"$left & $right & $mid")
      val ans = count(mid)
      if (ans < m) left = mid + 1
      else right = mid
    }

    count(left)
  }

  val result = find
  println(if (result == m) left else -1)
}


import java.util.Scanner
//remove if not needed
import scala.collection.JavaConversions._

object Power {

  def main(args: Array[String]) {
    val kbd = new Scanner(System.in)
    val n = kbd.nextDouble()
    val result = Math.pow(5, n).toInt
    val resultAsString = java.lang.Integer.toString(result)
    val length = resultAsString.length
    if (n <= 13) println(resultAsString.substring((length - 2))) else println("25")
  }
}


object A extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }

  val Array(m) = readInts(1)
  val Array(h1, a1) = readInts(2)
  val Array(x1, y1) = readInts(2)
  val Array(h2, a2) = readInts(2)
  val Array(x2, y2) = readInts(2)

  def ring(h0: Int, a: Int, x: Long, y: Int) = {
    val visited = Array.fill(m){ -1 }
    var h = h0
    var step = 0
    while (visited(h) < 0) {
      visited(h) = step
      h = ((x.toLong * h + y) % m).toInt
      step += 1
    }
    val cycleStart = visited(h)
    val cycleSize = step - cycleStart
    val extraSteps = visited(a)
    (extraSteps, cycleSize, cycleStart)
  }

  val (steps1, cycle1, cycleStart1) = ring(h1, a1, x1, y1)
  val (steps2, cycle2, cycleStart2) = ring(h2, a2, x2, y2)

  if (steps1 < 0 || steps2 < 0) println(-1)
  else {
    var step1 = steps1.toLong
    var step2 = steps2.toLong
    var i = 0
    while (i < 100000000) {
      if (step1 == step2) {
        println(step1)
        System.exit(0)
      } else if (step1 < step2 && steps1 >= cycleStart1) step1 += cycle1
      else if (step2 < step1 && steps2 >= cycleStart2) step2 += cycle2
      i += 1
    }
    println(-1)
  }
}


import scala.io.Source

object a15 {
  def main(args: Array[String]): Unit = {
    val Array(_,s) = Source.stdin.getLines().take(2).toArray
    println(if (s=="0")
      0
    else
      s"1${s.filter(_ == '0')}"
    )
  }

}


object _982A extends CodeForcesApp {
  import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._

  override def apply(io: IO): io.type = {
    val _ = io.read[Int]
    val seating = io.read[String]
    val isMaximal = !seating.contains("11") && !seating.startsWith("00") && !seating.endsWith("00") && !seating.contains("000") && seating != "0"
    io.write(if (isMaximal) "Yes" else "No")
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
  val printer = new PrintWriter(out, true)

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    tokenizers.headOption
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }

  object Read {
    implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    implicit val int                                                      : Read[Int]          = string.map(_.toInt)
    implicit val long                                                     : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                                   : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                                   : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                               : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                                 : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]                        : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]               : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                                  : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}


import java.io.PrintWriter
import java.util.Scanner

/**
 * Created by arseny on 07.02.15.
 */
object A extends App {

  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def nextInt = in.nextInt
  def nextLong = in.nextLong
  def nextDouble = in.nextDouble
  def nextString = in.next

  def solve() = {
    val n1 = nextInt
    val n2 = nextInt
    val k1 = nextInt
    val k2 = nextInt
    println(if (n1 > n2) "First" else "Second")
  }

  try {
    solve()
  } catch {
    case _: Exception => sys.exit(9999)
  } finally {
    out.flush()
    out.close()
  }
}


import scala.io.StdIn._
import scala.collection.mutable.ArrayBuffer

object Main {
  def main(args: Array[String]): Unit = {
    // println("please enter:")
    val n = readInt()
    val ps = readLine().split(" ").map(_.toInt)

    var ret = 0

    var curParity, lastParity, lastState, zeroSeqLen, even, odd, diffParity = 0
    var leadingZeros, trailingZeros = 0
    var leadingParity, trailingParity = 0
    var evenParity, oddParity = ArrayBuffer[Int]()
    var hasNum = false
    var prevNumParity = 0

    (ps :+ -1).foreach(x => {
      if (x == 0) { // zero
        lastState = 0
        zeroSeqLen += 1
        prevNumParity = 0
      } else if (x == -1) { // reach the end
        if (lastState == 0) trailingZeros = zeroSeqLen
        trailingParity = lastParity
      } else { // num
        if (x % 2 == 0) { // even
          even += 1
          curParity = 1
        } else { // odd
          odd += 1
          curParity = -1
        }
        if (prevNumParity != 0 && prevNumParity != curParity) {
          ret += 1
        }
        if (lastState == 0) {
          if (lastParity == 0) {
            leadingZeros = zeroSeqLen
            leadingParity = curParity
          } else if (lastParity == curParity) {
            if (curParity == 1)
              evenParity += zeroSeqLen
            else
              oddParity += zeroSeqLen
          } else {
            diffParity += 1
          }
          zeroSeqLen = 0
        }
        hasNum = true
        lastState = 1
        lastParity = curParity
        prevNumParity = curParity
      }
    })

    even = n / 2 - even
    odd = (n + 1) / 2 - odd

    // println(f"$leadingZeros, $trailingZeros")
    // println("even:")
    // for (i <- evenParity)
    //   println(i)
    // println("odd:")
    // for (i <- oddParity)
    //   println(i)
    // println(f"diff: $diffParity, even: $even, odd: $odd")

    if (n == 1) {
      ret = 0
    } else if (!hasNum) { // if all bulbs are removed
      ret = 1
    } else {
      evenParity = evenParity.sorted
      oddParity = oddParity.sorted
      var (evenLeft, evenZeros) = takeSumLim(evenParity, 0, even)
      var (oddLeft, oddZeros) = takeSumLim(oddParity, 0, odd)
      // println(f"even: $even, odd: $odd")
      // println(
      //   f"leading parity: $leadingParity, " +
      //     f"trailing parity: $trailingParity"
      // )
      ret += 1
      if (leadingParity == 1 && leadingZeros <= evenLeft) {
        evenLeft -= leadingZeros
        ret -= 1
      } else if (leadingParity == -1 && leadingZeros <= oddLeft) {
        oddLeft -= leadingZeros
        ret -= 1
      }
      ret += 1
      if (trailingParity == 1 && trailingZeros <= evenLeft ||
          trailingParity == -1 && trailingZeros <= oddLeft) {
        ret -= 1
      }
      ret += diffParity
      ret += 2 * evenZeros
      ret += 2 * oddZeros
    }

    println(ret)
  }

  def takeSumLim(seq: ArrayBuffer[Int], z: Int, lim: Int): (Int, Int) =
    if (seq.length == 0)
      (lim - z, 0)
    else if (z + seq(0) <= lim)
      takeSumLim(seq.tail, z + seq(0), lim)
    else
      (lim - z, seq.length)

}


object Lesha extends App {

  case class State(val boundaries: List[Int], val hasNonZeros: Boolean, val sum: Int)

  val n: Int = readLine.toInt
  val aa: Seq[Int] = readLine.split(' ').map(_.toInt)

  val sums: Seq[Int] = aa.scanLeft(0)(_ + _)
  val r = (sums.zipWithIndex.toMap + (sums.head -> 0, sums.last -> (sums.size - 1))).values.toList.sorted
  val results = r match {
    case 0 :: x => x
    case x: List[Int] => x
  }

  if (aa.forall(_ == 0)) {
    println("NO")
  }
  else {
    println("YES")
    println(results.length)
    (0 :: results).map(_ + 1) zip results foreach {
      case (a, b) => println(a + " " + b)
    }
  }

}


object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(x, y) = in.next().split(' ').map(_.toInt)
  val d = Math.sqrt(x * x + y * y)
  if (d == d.toInt)
    println("black")
  else if ((x > 0 && y > 0) || (x < 0 && y < 0))
    if (d.toInt % 2 == 0)
      println("black")
    else
      println("white")
  else
  if (d.toInt % 2 == 0)
    println("white")
  else
    println("black")
}


import scala.annotation.tailrec, scala.collection.mutable
import CodeForcesApp._
object _557A extends CodeForcesApp[List[Int]]({ scanner => import scanner._
  val n = nextInt
  val rs = List.fill(3)((nextInt, nextInt))
  val (mins, maxs) = (rs.map(_._1), rs.map(_._2))
  var ans = mins
  while(ans.sum < n) {
    val diff = n - ans.sum
    var found = false
    ans = ans zip maxs map { case (c, m) =>
      if(found) {
        c
      } else if(c == m) {
        c
      } else {
        found = true
        (c + diff) min m
      }
    }
  }
  ans
}) {
  override def format(result: List[Int]) = result mkString " "
}
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: A): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  val modulus: Int = 1000000007
  def when[A](x: Boolean)(f: => A): Option[A] = if (x) Some(f) else None
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
}


import scala.io.StdIn._
object Solution {
  def main(args: Array[String]): Unit = {
    val Array(k2, k3, k5, k6) = readLine.split(" ").map(_.toInt)
    val b = Math.min(k2, Math.min(k5, k6))
    val s = Math.min(k3, k2 - b)
    println(b * 256 + s * 32)
  }
}


object B{
  def main(args: Array[String]){

    //a~b
    val(a,b)={
      val sp=readLine.split(" ")
      val (p,d)=(sp(0).toLong, sp(1).toLong)
      (p-d,p)
    }

    //i個の9でmax調べる
    val ans=(1 to 18).filter{i=>
      Math.pow(10, i)<=b
    }.map{i=>
      val n1=Math.pow(10, i).toLong
      ((b+1)-(b+1)%n1-1)
    }.filter{ans=>
      a<=ans && ans<=b
    }.lastOption.getOrElse(b.toLong)

    println(ans)

  }
}


object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val S = ns()

    val evens = S.take((S.length - 1) / 2 + 1).reverse
    val odds = S.drop(evens.length)
    val T = Array.ofDim[Char](S.length)
    REP(evens.length) { i =>
      T(i * 2) = evens(i)
    }
    REP(odds.length) { i =>
      T(i * 2 + 1) = odds(i)
    }
    out.println(T.mkString)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    REP(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    REP(n) { i =>
      REP(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }

  def cumSum(as: Array[Int]) = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}


object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val N, M = ni()
    val A = na(N)
    val mx = A.max

    val vacant = (A map (mx - _)).sum
    val needs = max(0, M - vacant)
    val additional = needs / N + (if (needs % N != 0) 1 else 0)

    out.println(s"${additional + mx} ${mx+M}")
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int): Array[Int] = map(n)(_ => ni())
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

  def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    rep(as.length)(i => s += as(i))
    s
  }
}


object B {
  import InOut._
  def main(args: Array[String]): Unit = {

    val k = nextLong

    val xs = Array.fill(10)(1L)
    var cnt = 1L
    while (cnt < k) {
      var i = xs.indices.minBy(xs)
      cnt /= xs(i)
      xs(i) += 1
      cnt *= xs(i)
    }

    val s = "codeforces".zip(xs).map { case (c, count) =>
      c.toString * count.toInt
    }.mkString

    out.println(s)

    out.flush()
  }

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def nextInts(n: Int) = Array.fill(n) { nextInt }
    def nextLongs(n: Int) = Array.fill(n) { nextLong }
    def nextBigs(n: Int) = Array.fill(n) { nextBig }
    def nextLine = in.readLine
  }
}


object Solution {
    def sqr(n: Int) = n * n

    def solve(n: String): Int = {
        if(n.head == '0')return -1
        if(sqr(Math.sqrt(n.toInt).toInt).toString() == n)return 0
        if(n.length == 1)return -1
        var ans = -1
        for(i <- 0 until n.length()){
            val substr = n.substring(0, i) + n.substring(i + 1);
            val answer = solve(substr)
            if(answer != -1 && (ans == -1 || ans > answer + 1))ans = answer + 1
        }
        return ans
    }

    def main(args: Array[String]) {
        val n = readLine
        println(solve(n))
    }
}


import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn

object Codeforces1011A {

  def getWeight(char: Char): Int = char - 'a' + 1

  def getMinimumWeight(n: Int, k: Int, stages: String): Int = {
    val stageSet = stages.toSet

    val rocket = new ArrayBuffer[Char]()

    var previousCharAdded = false
    for (ch <- 'a' to 'z') {
      if ((stageSet contains ch) && !previousCharAdded) {
        rocket.append(ch)
        previousCharAdded = true
      } else {
        previousCharAdded = false
      }
    }

    if (rocket.size < k) -1
    else rocket.take(k).map(getWeight).sum
  }

  def main(args: Array[String]): Unit = {
    val Array(n, k) = StdIn.readLine.trim.split(" ").map(_.toInt)
    val stages = StdIn.readLine()
    val weight = getMinimumWeight(n, k, stages)
    println(weight)
  }
}


object _801A extends CodeForcesApp {
  import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._

  override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}
    val s = read[String]
    val ans = s.indices
      .flatMap(i => Seq(s.updated(i, 'V'), s.updated(i, 'K')))
      .maxWith(count)
      .get

    write(ans max count(s))
  }

  def count(s: String) = s.sliding(2).count(_ == "VK")
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
    def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
  val printer = new PrintWriter(out, true)

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    when(tokenizers.nonEmpty)(tokenizers.head)
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                      : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}


object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val N, K = ni()
    val d = divisors(N)

    var ans = 1e18.toLong
    REP(d.length) { i =>
      if (d(i) < K) {
        val b = d(i)
        val a = N / b
        val x = a.toLong * K + b
        ans = min(ans, x)
      }
    }

    out.println(ans)
  }

  /**
    * O(√x)
    */
  def divisors(x: Int): Array[Int] = {
    val pre = ArrayBuffer[Int]()
    val post = ArrayBuffer[Int]()
    REP(math.sqrt(x).toInt, 1) { d =>
      if (x % d == 0) {
        pre += d
        if (d * d != x) post += x / d
      }
    }

    val res = Array.ofDim[Int](pre.length + post.length)
    REP(pre.length)(i => res(i) = pre(i))
    val preLen = pre.length
    REP_r(post.length)(i => res(i + preLen) = post(i))
    res
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    REP(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    REP(n) { i =>
      REP(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }

  def cumSum(as: Array[Int]) = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}


import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._

object _658A extends CodeForcesApp {
  override def apply(io: IO) = {
    val n, c = io[Int]
    val p, t = io[IndexedSeq, Int](n)
    io += ((score(p, t, c) - score(p.reverse, t.reverse, c)).signum match {
      case 0 => "Tie"
      case 1 => "Limak"
      case -1 => "Radewoosh"
    })
  }

  def score(p: Seq[Int], t: Seq[Int], c: Int): Int = {
    var time, score = 0
    for {
      i <- p.indices
    }  {
      time += t(i)
      score += ((p(i) - c*time) max 0)
    }
    score
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = t.head.ensuring(t.size == 1)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sum[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount: Int = java.lang.Long.bitCount(x)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)
  }
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def  asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default
  }
  def memoize[I] = new {
    def apply[O](f: I => O): I => O = new mutable.HashMap[I, O]() {
      override def apply(key: I) = getOrElseUpdate(key, f(key))
    }
  }
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  val mod: Int = (1e9 + 7).toInt
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

class IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    if (tokenizers.nonEmpty) Some(tokenizers.head) else None
  }

  def apply[A](implicit read: IO.Read[A]): A = read.apply(this)
  def apply[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(apply).to[C]

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine(): String = till("\n\r")

  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty

  var separator = " "
  private[this] var isNewLine = true

  def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {
    write(this)(x)
    this
  }
  def appendNewLine(): this.type = {
    println()
    this
  }

  override def print(obj: String) = {
    if (isNewLine) isNewLine = false else super.print(separator)
    super.print(obj)
  }
  override def println() = if (!isNewLine) {
    super.println()
    isNewLine = true
  }
  override def close() = {
    flush()
    in.close()
    super.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r[C, A](r[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val boolean                                      : Read[Boolean]      = string.map(_.toBoolean)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r[A], r[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r[A], r[B], r[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))
  }
  trait Write[-A] {
    def apply(out: PrintWriter)(x: A): Unit
  }
  trait DefaultWrite {
    implicit def any[A]: Write[A] = Write(_.toString)
  }
  object Write extends DefaultWrite {
    def apply[A](f: A => String) = new Write[A] {
      override def apply(out: PrintWriter)(x: A) = out.print(f(x))
    }
    implicit val boolean: Write[Boolean] = Write(b => if (b) "YES" else "NO")
    implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {
      override def apply(out: PrintWriter)(xs: Traversable[A]) = {
        xs foreach write(out)
        out.println()
      }
    }
  }
}


import scala.io.StdIn

/**
  * Created by a.kosarev1 on 23.01.2017.
  */
object Solution extends App {

  val stdIn = StdIn.readLine();
  val input = stdIn.split(" ").map(_.toInt)

  println(calculateWeeks(input(0), input(1)))

  def calculateWeeks(month: Int, dow: Int): Int = {
    val daysCount = 28 + (month + month / 8) % 2 + 2 % month + 2 * (1 / month)

    def calcWeeks(weekCount: Int, dow: Int, acc: Int): Int = {
      if (acc == daysCount) weekCount
      else if (dow % 7 == 0) calcWeeks(weekCount + 1, 1, acc + 1)
      else calcWeeks(weekCount, dow + 1, acc + 1)
    }
    calcWeeks(1, dow, 1)
  }

}


object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val a = (1 to 4).map(_ => readLine().split(" ").map(_.toInt))
    val mapped = a.map(row => row(0).min(row(1)) + row(2).min(row(3)))
    val min = mapped.zipWithIndex.minBy(_._1)
    if (min._1 > n) println("-1")
    else {
      val row = a(min._2)
      val v1 = row(0).min(row(1))
      val v2 = n - v1
      println((min._2 + 1) + " " + v1 + " " + v2)
    }
  }
}


import scala.math._, scala.io.StdIn._

object B extends App {
  val n = readLong

  var r = digits(n).product
  var k = 10L
  while (k <= n) {
    val r1 = digits((n / k) * k - 1).product
    if (r1 > r)
      r = r1
    k *= 10
  }
  println(r)

  def digits(n: Long) = n.toString.map(_.asDigit)

  def readInts() = readLine.split(" ").map(_.toInt)
}


import scala.io.StdIn._

object Main extends App {
    var line = readLine();
    val n = line.toInt;
    def solve (n : Int ) = (0 to 9).
    map( i => math.pow(10,i) ).
    filter( i => i<= n ).
    foldLeft[Double](0)((acc,i) => acc + n - i + 1);
    println((solve(n) / 1).asInstanceOf[Long]);
}


object B extends App {
  def check(y: Int, p: Int): Boolean = {
    val t = p min (math.sqrt(y).toInt + 1)
    for (x <- 2 to t)
      if (y % x == 0) return false
    true
  }

  def branch(y: Int, p: Int): Int =
    if (y == p) -1
    else if (check(y, p)) y
    else branch(y - 1, p)

  val Array(p, y) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  println(branch(y, p))
}


import java.util.Scanner

object C extends App {

  val sc = new Scanner(System.in)

  val n = sc.nextLong()
  val m = sc.nextLong()

  if (n < m) println(n)
  else {
    val d = 1 + 8 * (n - m)
    val root = ((-1.0 + math.sqrt(d)) / 2.0).ceil.toLong
    // fix for floating point precision
    if (n - m - (root * (root + 1)) / 2 <= 0) println(root + m)
    else println(root + m + 1)
  }
}


import scala.io.StdIn.readLine

/**
 * @author slie742
 */
object NearlyLucky {

  def main(args: Array[String]) {
    val lucky = readLine.count { c => c == '4' || c == '7'}
    if (lucky == 4 || lucky == 7)
      println("YES")
    else
      println("NO")
  }

}


object A732 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

  def readInts(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)
  }

  def readLongs(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)
  }

  def readBigs(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))
  }

  def main(args: Array[String]): Unit = {
    val Array(k, r) = readInts(2)
    var num = 1
    var break = false
    while(!break && num <= 10) {
      if(num*k % 10 == 0) {
        println(num)
        break = true
      } else if ((num*k - r)%10 == 0) {
        println(num)
        break = true
      }
      num += 1
    }
  }
}


import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val mod = (1e9 + 7).toInt
  val dp = Array.ofDim[Int](k + 1, n + 1)

  (0 to n).foreach { i => dp(0)(i) = 1}

  (1 to k).foreach { i =>
    var j = 1
    while (j <= n) {
      (j to n by j).foreach { el =>
        dp(i)(j) += dp(i - 1)(el)
        dp(i)(j) %= mod
      }
      j += 1
    }
  }

  println(dp(k)(1))
}


import scala.collection.mutable

object B extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(n) = readInts(1)

  val rByL = Array.fill(n){ mutable.Queue.empty[Int] }

  for {
    r <- 0 to n - 1
    l <- r + 1 to n
  } rByL(r) += l

  var res = 0
  var done = false

  while (!done) {
    var r = 0
    while (r < n && rByL(r).isEmpty) r += 1
    if (r == n) done = true
    else {
      res += 1
      while (r < n) {
        val l = rByL(r).dequeue()
        r = l
        while (r < n && rByL(r).isEmpty) r += 1
      }
    }
  }

  println(res)
}