import java.util.Scanner

object Main extends App {

  def readALine(c:Int, ac:List[Int]=Nil):List[Int] =
    if (c > 0) readALine(c-1, sc.nextInt::ac) else ac.reverse
  // def readLines(r:Int, c:Int, ac:List[List[Int]]):List[List[Int]] =
  //   if (r > 0) readLines(r-1, c, readALine(c, Nil)::ac) else ac.reverse
  val sc = new Scanner(System.in)
  val N,M,K = sc.nextInt
  val Ai = readALine(N)
  val Bi = readALine(M)

  def solver(al:List[Int], bl:List[Int], ac:Int, count:Int):Int = {
    (al, bl) match {
      case (Nil, Nil) => count
      case (a::as, Nil) => if (ac+a > K) count else solver(as, Nil, ac+a, count+1)
      case (Nil, b::bs) => if (ac+b > K) count else solver(Nil, bs, ac+b, count+1)
      case (a::as, b::bs) if a >  b => if (ac+b > K) count else solver(al, bs, ac+b, count+1)
      case (a::as, b::bs) if a <= b => if (ac+a > K) count else solver(as, bl, ac+a, count+1)
    }
  }

  // println(s"Ai:$Ai Bi:$Bi")
  println(solver(Ai, Bi, 0, 0))

}


//import java.util.Scanner

import java.io._
import java.nio.file.Files._
import java.nio.file.Path
import java.util.StringTokenizer

import scala.collection.immutable._
import scala.io.Codec
import scala.language.postfixOps

/**
  * Scala implementation of a faster java.util.Scanner
  * See: http://codeforces.com/blog/entry/7018
  */

class Scanner(reader: LineNumberReader) extends Iterable[String] with AutoCloseable {
  def this(reader: BufferedReader) = this(new LineNumberReader(reader))

  def this(reader: Reader) = this(new BufferedReader(reader))

  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

  def this(path: Path)(implicit codec: Codec) = this(newBufferedReader(path, codec.charSet))

  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

  def this(str: String) = this(new StringReader(str))

  override def iterator: Iterator[String] = for {
    line <- Iterator.continually(reader.readLine()).takeWhile(_ != null)
    tokenizer = new StringTokenizer(line)
    tokens <- Iterator.continually(tokenizer).takeWhile(_.hasMoreTokens)
  } yield tokens.nextToken()

  private[this] var current = iterator

  def hasNext: Boolean = current.hasNext

  @inline def next(): String = current.next()

  /**
    * This is different from Java's scanner.nextLine
    * The Java one is a misnomer since it actually travel to end of current line
    * This one actually does fetch the next line
    */
  def nextLine(): String = {
    val line = reader.readLine()
    current = iterator
    line
  }

  def lineNumber: Int = reader.getLineNumber

  def nextString(): String = next()

  def nextBoolean(): Boolean = next().toBoolean

  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

  def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

  def nextFloat(): Float = next().toFloat

  def nextDouble(): Double = next().toDouble

  def nextBigDecimal(): BigDecimal = BigDecimal(next())

  override def close(): Unit = reader.close()
}

class IUnionFind(val size: Int) {

  private case class Node(var parent: Option[Int], var treeSize: Int)

  private val nodes = Array.fill[Node](size)(Node(None, treeSize = 1))

  def union(t1: Int, t2: Int): IUnionFind = {
    if (t1 == t2) return this

    val root1 = root(t1)
    val root2 = root(t2)
    if (root1 == root2) return this

    val node1 = nodes(root1)
    val node2 = nodes(root2)

    if (node1.treeSize < node2.treeSize) {
      node1.parent = Some(t2)
      node2.treeSize += node1.treeSize
    } else {
      node2.parent = Some(t1)
      node1.treeSize += node2.treeSize
    }
    this
  }

  def connected(t1: Int, t2: Int): Boolean = t1 == t2 || root(t1) == root(t2)

  def root(t: Int): Int = nodes(t).parent match {
    case None => t
    case Some(p) =>
      nodes(t).parent = Some(root(p))
      nodes(t).parent.get
  }

  def nodeSize(t: Int): Int = nodes(root(t)).treeSize
}

object Main {
  def solve(sc: => Scanner): Unit = {
    val N, M = sc.nextInt()
    val K = sc.nextLong()
    val A = Array.fill(N)(sc.nextLong())
    val B = Array.fill(M)(sc.nextLong())
    println(recursive(A.reverse ++ B, 0, N, N, N + M, A.sum, K))
  }

  @scala.annotation.tailrec
  def recursive(A: Array[Long], left: Int, right: Int, leftMax: Int, rightMax: Int, sum: Long, K: Long, ans: Int = 0): Long = {
    val nextAns = if (sum <= K) Math.max(ans, right - left) else ans
    if (left == leftMax + 1) nextAns
    else if (right != rightMax && sum <= K) recursive(A, left, right + 1, leftMax, rightMax, sum + A(right), K, nextAns)
    else recursive(A, left + 1, right, leftMax, rightMax, sum - A(left), K, nextAns)
  }

  @scala.annotation.tailrec
  def recursive2(N: Long, now: Long = 1): Long = {
    if (N >= now) recursive2(N - now, now + 1)
    else now - 1
  }

  def flip(A: Array[Boolean], B: Array[(Int, Long)]): Array[(Int, Long)] = {
    B.map { case (index, _) =>
      (index, (if (0 < index && A(index - 1)) B(index - 1)._2 else 0L) + (if (index + 1 < B.length && !A(index + 1)) B(index + 1)._2 else 0L))
    }
  }

  val mod: Long = (1e9 + 7).toLong

  @scala.annotation.tailrec
  def factorial(now: Long, ans: Long = 1): Long = {
    if (now == 0) 0 else if (now == 1) ans else factorial(now - 1, now * ans)
  }

  implicit class implicitInt(val N: Int) {
    def times[B](function: Int => B): IndexedSeq[B] = (0 until N).map(function)
  }

  def calc(input: (Long, Long, Long, Long, Long, Long)): Long = {
    input match {
      case (a, b, c, x, y, z) =>
        var ans: Long = Long.MaxValue
        if (b >= 3 && (a >= 2 || c >= 2)) {
          ans = Math.min(ans, Math.max(a - (b - 1), 0) * x + Math.max(c - Math.min(a - 1, b - 2), 0) * z)
          ans = Math.min(ans, Math.max(a - Math.min(c - 1, b - 2), 0) * x + Math.max(c - (b - 1), 0) * z)
        }
        //        println(ans)
        if (b >= 2 && (a >= b && c >= b + 1)) {
          ans = Math.min(ans, y + Math.max(0, a - (c - 1)) * x)
        }
        //        println(ans)
        if (b >= 2 && (a >= b + 1 && c >= b)) {
          ans = Math.min(ans, y + Math.max(0, c - (a - 1)) * z)
        }
        //        println(ans)
        if (a >= 2 && c >= 2)
          if (a != c)
            ans = Math.min(ans, Math.max(0, b - (Math.min(a, c) - 1)) * y)
          else if (a >= 3 && c >= 3)
            ans = Math.min(ans, Math.max(0, b - (Math.min(a, c) - 2)) * y + Math.min(x, z))
        //        println(ans)
        if (ans == Long.MaxValue) ans = -1
        ans
    }
  }

  def time(s: String): Int =
    s.substring(0, 2).toInt * 60 + s.substring(3, 5).toInt

  /*
  def getPermutation(begin: Long = 0): LazyList[Long] =
    LazyList.cons(begin, getPermutation(begin + 1))

  def getFibonacci(prevprev: Long = 0, prev: Long = 1): LazyList[Long] =
    LazyList.cons(prevprev, getFibonacci(prev, prevprev + prev))

  @scala.annotation.tailrec
  def recursive2(X: Set[Long], Y: LazyList[Long]): Long = if (X.contains(Y.head)) X.size else recursive2(X + Y.head, Y.tail)
*/
  def check(i: Int, X: String): Long = {
    if (X == "") 0 else check(i, X.tail) * i + X.head.toString.toLong
  }

  def shift(n: Long): Long = {
    if (n == 0) 0
    else if (n == 1) 1
    else shift(n - 1) << 1
  }

  def unShift(n: Long): Long = {
    if (n == 0) 0
    else unShift(n >> 1) + 1
  }

  @scala.annotation.tailrec
  def gcd(i: Long, j: Long): Long = {
    if (i < j) gcd(j, i)
    else if (j == 0) i
    else gcd(j, i % j)
  }

  def primeFactors(i: Long): List[Long] = primeFactors_(i, 1).sorted

  def primeFactors_(i: Long, j: Long): List[Long] = {
    if (j * j > i) List.empty else if (i % j == 0) primeFactors_(i, j + 1) ++ List[Long](j, i / j) else primeFactors_(i, j + 1)
  }

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

/*
object Util {
  def getPermutation(begin: Long = 0): LazyList[Long] =
    LazyList.cons(begin, getPermutation(begin + 1))

  def getPrimeList: LazyList[Long] =
    getPrimeListRecursive(getPermutation(begin = 2))

  private def getPrimeListRecursive(A: LazyList[Long]): LazyList[Long] =
    LazyList.cons(A.head, getPrimeListRecursive(A.tail.filter(_ % A.head != 0)))

  def fib(a: Long = 0, b: Long = 1, mod: Long = Long.MaxValue): LazyList[Long] = a #:: fib(b % mod, (a + b) % mod, mod)
}

 */

object ArabicRoman {

  type =?>[A, B] = PartialFunction[A, B]

  private val codeTable: List[(Int, String)] = List(
    (1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"),
    (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"))

  val arabicToRoman: Int =?> String = {
    case src if src >= 1 && src <= 3999 =>

      @scala.annotation.tailrec
      def convert(left: Int, cont: String = "", code: List[(Int, String)] = codeTable): String = {
        val (unitVal, unitChar) = code.head
        left - unitVal match {
          case n if n == 0 => cont + unitChar
          case n if n > 0 => convert(n, cont + unitChar, code)
          case _ => convert(left, cont, code.tail)
        }
      }

      convert(src)
  }

  val romanToArabic: String =?> Int = {
    case src if Option(src).exists { s => {
      s.nonEmpty && """[^MDCLXVI]""".r.findFirstMatchIn(s.toUpperCase).isEmpty
    }
    } =>

      @scala.annotation.tailrec
      def convert(left: String, cont: Int = 0, code: List[(Int, String)] = codeTable): Int = {
        val (unitVal, unitChar) = code.head
        left.splitAt(unitChar.length) match {
          case ("", _) => cont
          case (`unitChar`, tail) => convert(tail, cont + unitVal, code)
          case _ => convert(left, cont, code.tail)
        }
      }

      convert(src.toUpperCase())
  }
}

object PowMod {
  def naivePowMod(a: Long, k: Long, m: Long): Long = {
    var t: Long = 1
    val aMod: Long = a % m

    for (_ <- 1L to k) {
      t = ((t % m) * aMod) % m
    }
    t.toInt
  }

  def powMod(a: Long, k: Long, m: Long): Long = {
    if (k == 0) 1
    else {
      val t = powMod(a, k / 2, m)
      if ((k % 2) == 0) (t * t) % m else (((t * t) % m) * a) % m
    }
  }
}

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Score : 300 points

Problem Statement

We have two desks: A and B. Desk A has a vertical stack of N books on it, and Desk B similarly has M books on it.

It takes us A_i minutes to read the i-th book from the top on Desk A (1 \leq i \leq N), and B_i minutes to read the i-th book from the top on Desk B (1 \leq i \leq M).

Consider the following action:

Choose a desk with a book remaining, read the topmost book on that desk, and remove it from the desk.

How many books can we read at most by repeating this action so that it takes us at most K minutes in total? We ignore the time it takes to do anything other than reading.

Constraints

1 \leq N, M \leq 200000

1 \leq K \leq 10^9

1 \leq A_i, B_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M K
A_1 A_2 \ldots A_N
B_1 B_2 \ldots B_M

Output

Print an integer representing the maximum number of books that can be read.

Sample Input 1

3 4 240
60 90 120
80 150 80 150

Sample Output 1

3

In this case, it takes us 60, 90, 120 minutes to read the 1-st, 2-nd, 3-rd books from the top on Desk A, and 80, 150, 80, 150 minutes to read the 1-st, 2-nd, 3-rd, 4-th books from the top on Desk B, respectively.

We can read three books in 230 minutes, as shown below, and this is the maximum number of books we can read within 240 minutes.

Read the topmost book on Desk A in 60 minutes, and remove that book from the desk.

Read the topmost book on Desk B in 80 minutes, and remove that book from the desk.

Read the topmost book on Desk A in 90 minutes, and remove that book from the desk.

Sample Input 2

3 4 730
60 90 120
80 150 80 150

Sample Output 2

7

Sample Input 3

5 4 1
1000000000 1000000000 1000000000 1000000000 1000000000
1000000000 1000000000 1000000000 1000000000

Sample Output 3

0

Watch out for integer overflows.

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


//import java.util.Scanner

import java.io._
import java.nio.file.Files._
import java.nio.file.Path
import java.util.StringTokenizer

import scala.collection.immutable._
import scala.io.Codec
import scala.language.postfixOps

/**
  * Scala implementation of a faster java.util.Scanner
  * See: http://codeforces.com/blog/entry/7018
  */

class Scanner(reader: LineNumberReader) extends Iterable[String] with AutoCloseable {
  def this(reader: BufferedReader) = this(new LineNumberReader(reader))

  def this(reader: Reader) = this(new BufferedReader(reader))

  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

  def this(path: Path)(implicit codec: Codec) = this(newBufferedReader(path, codec.charSet))

  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

  def this(str: String) = this(new StringReader(str))

  override def iterator: Iterator[String] = for {
    line <- Iterator.continually(reader.readLine()).takeWhile(_ != null)
    tokenizer = new StringTokenizer(line)
    tokens <- Iterator.continually(tokenizer).takeWhile(_.hasMoreTokens)
  } yield tokens.nextToken()

  private[this] var current = iterator

  def hasNext: Boolean = current.hasNext

  @inline def next(): String = current.next()

  /**
    * This is different from Java's scanner.nextLine
    * The Java one is a misnomer since it actually travel to end of current line
    * This one actually does fetch the next line
    */
  def nextLine(): String = {
    val line = reader.readLine()
    current = iterator
    line
  }

  def lineNumber: Int = reader.getLineNumber

  def nextString(): String = next()

  def nextBoolean(): Boolean = next().toBoolean

  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

  def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

  def nextFloat(): Float = next().toFloat

  def nextDouble(): Double = next().toDouble

  def nextBigDecimal(): BigDecimal = BigDecimal(next())

  override def close(): Unit = reader.close()
}

class IUnionFind(val size: Int) {

  private case class Node(var parent: Option[Int], var treeSize: Int)

  private val nodes = Array.fill[Node](size)(Node(None, treeSize = 1))

  def union(t1: Int, t2: Int): IUnionFind = {
    if (t1 == t2) return this

    val root1 = root(t1)
    val root2 = root(t2)
    if (root1 == root2) return this

    val node1 = nodes(root1)
    val node2 = nodes(root2)

    if (node1.treeSize < node2.treeSize) {
      node1.parent = Some(t2)
      node2.treeSize += node1.treeSize
    } else {
      node2.parent = Some(t1)
      node1.treeSize += node2.treeSize
    }
    this
  }

  def connected(t1: Int, t2: Int): Boolean = t1 == t2 || root(t1) == root(t2)

  def root(t: Int): Int = nodes(t).parent match {
    case None => t
    case Some(p) =>
      nodes(t).parent = Some(root(p))
      nodes(t).parent.get
  }

  def nodeSize(t: Int): Int = nodes(root(t)).treeSize
}

object Main {
  def solve(sc: => Scanner): Unit = {
    val N, M = sc.nextInt()
    val K = sc.nextLong()
    val A = Array.fill(N)(sc.nextLong())
    val B = Array.fill(M)(sc.nextLong())
    println(recursive(A.reverse ++ B, 0, N, N + M, A.sum, K))
  }

  @scala.annotation.tailrec
  def recursive(A: Array[Long], left: Int, right: Int, rightMax: Int, sum: Long, K: Long, ans: Int = 0): Long = {
    val nextAns = if (sum <= K) Math.max(ans, right - left) else ans
    if (left == rightMax) nextAns
    else if (right != rightMax && sum <= K) recursive(A, left, right + 1, rightMax, sum + A(right), K, nextAns)
    else recursive(A, left + 1, right, rightMax, sum - A(left), K, nextAns)
  }

  @scala.annotation.tailrec
  def recursive2(N: Long, now: Long = 1): Long = {
    if (N >= now) recursive2(N - now, now + 1)
    else now - 1
  }

  def flip(A: Array[Boolean], B: Array[(Int, Long)]): Array[(Int, Long)] = {
    B.map { case (index, _) =>
      (index, (if (0 < index && A(index - 1)) B(index - 1)._2 else 0L) + (if (index + 1 < B.length && !A(index + 1)) B(index + 1)._2 else 0L))
    }
  }

  val mod: Long = (1e9 + 7).toLong

  @scala.annotation.tailrec
  def factorial(now: Long, ans: Long = 1): Long = {
    if (now == 0) 0 else if (now == 1) ans else factorial(now - 1, now * ans)
  }

  implicit class implicitInt(val N: Int) {
    def times[B](function: Int => B): IndexedSeq[B] = (0 until N).map(function)
  }

  def calc(input: (Long, Long, Long, Long, Long, Long)): Long = {
    input match {
      case (a, b, c, x, y, z) =>
        var ans: Long = Long.MaxValue
        if (b >= 3 && (a >= 2 || c >= 2)) {
          ans = Math.min(ans, Math.max(a - (b - 1), 0) * x + Math.max(c - Math.min(a - 1, b - 2), 0) * z)
          ans = Math.min(ans, Math.max(a - Math.min(c - 1, b - 2), 0) * x + Math.max(c - (b - 1), 0) * z)
        }
        //        println(ans)
        if (b >= 2 && (a >= b && c >= b + 1)) {
          ans = Math.min(ans, y + Math.max(0, a - (c - 1)) * x)
        }
        //        println(ans)
        if (b >= 2 && (a >= b + 1 && c >= b)) {
          ans = Math.min(ans, y + Math.max(0, c - (a - 1)) * z)
        }
        //        println(ans)
        if (a >= 2 && c >= 2)
          if (a != c)
            ans = Math.min(ans, Math.max(0, b - (Math.min(a, c) - 1)) * y)
          else if (a >= 3 && c >= 3)
            ans = Math.min(ans, Math.max(0, b - (Math.min(a, c) - 2)) * y + Math.min(x, z))
        //        println(ans)
        if (ans == Long.MaxValue) ans = -1
        ans
    }
  }

  def time(s: String): Int =
    s.substring(0, 2).toInt * 60 + s.substring(3, 5).toInt

  /*
  def getPermutation(begin: Long = 0): LazyList[Long] =
    LazyList.cons(begin, getPermutation(begin + 1))

  def getFibonacci(prevprev: Long = 0, prev: Long = 1): LazyList[Long] =
    LazyList.cons(prevprev, getFibonacci(prev, prevprev + prev))

  @scala.annotation.tailrec
  def recursive2(X: Set[Long], Y: LazyList[Long]): Long = if (X.contains(Y.head)) X.size else recursive2(X + Y.head, Y.tail)
*/
  def check(i: Int, X: String): Long = {
    if (X == "") 0 else check(i, X.tail) * i + X.head.toString.toLong
  }

  def shift(n: Long): Long = {
    if (n == 0) 0
    else if (n == 1) 1
    else shift(n - 1) << 1
  }

  def unShift(n: Long): Long = {
    if (n == 0) 0
    else unShift(n >> 1) + 1
  }

  @scala.annotation.tailrec
  def gcd(i: Long, j: Long): Long = {
    if (i < j) gcd(j, i)
    else if (j == 0) i
    else gcd(j, i % j)
  }

  def primeFactors(i: Long): List[Long] = primeFactors_(i, 1).sorted

  def primeFactors_(i: Long, j: Long): List[Long] = {
    if (j * j > i) List.empty else if (i % j == 0) primeFactors_(i, j + 1) ++ List[Long](j, i / j) else primeFactors_(i, j + 1)
  }

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

/*
object Util {
  def getPermutation(begin: Long = 0): LazyList[Long] =
    LazyList.cons(begin, getPermutation(begin + 1))

  def getPrimeList: LazyList[Long] =
    getPrimeListRecursive(getPermutation(begin = 2))

  private def getPrimeListRecursive(A: LazyList[Long]): LazyList[Long] =
    LazyList.cons(A.head, getPrimeListRecursive(A.tail.filter(_ % A.head != 0)))

  def fib(a: Long = 0, b: Long = 1, mod: Long = Long.MaxValue): LazyList[Long] = a #:: fib(b % mod, (a + b) % mod, mod)
}

 */

object ArabicRoman {

  type =?>[A, B] = PartialFunction[A, B]

  private val codeTable: List[(Int, String)] = List(
    (1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"),
    (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"))

  val arabicToRoman: Int =?> String = {
    case src if src >= 1 && src <= 3999 =>

      @scala.annotation.tailrec
      def convert(left: Int, cont: String = "", code: List[(Int, String)] = codeTable): String = {
        val (unitVal, unitChar) = code.head
        left - unitVal match {
          case n if n == 0 => cont + unitChar
          case n if n > 0 => convert(n, cont + unitChar, code)
          case _ => convert(left, cont, code.tail)
        }
      }

      convert(src)
  }

  val romanToArabic: String =?> Int = {
    case src if Option(src).exists { s => {
      s.nonEmpty && """[^MDCLXVI]""".r.findFirstMatchIn(s.toUpperCase).isEmpty
    }
    } =>

      @scala.annotation.tailrec
      def convert(left: String, cont: Int = 0, code: List[(Int, String)] = codeTable): Int = {
        val (unitVal, unitChar) = code.head
        left.splitAt(unitChar.length) match {
          case ("", _) => cont
          case (`unitChar`, tail) => convert(tail, cont + unitVal, code)
          case _ => convert(left, cont, code.tail)
        }
      }

      convert(src.toUpperCase())
  }
}

object PowMod {
  def naivePowMod(a: Long, k: Long, m: Long): Long = {
    var t: Long = 1
    val aMod: Long = a % m

    for (_ <- 1L to k) {
      t = ((t % m) * aMod) % m
    }
    t.toInt
  }

  def powMod(a: Long, k: Long, m: Long): Long = {
    if (k == 0) 1
    else {
      val t = powMod(a, k / 2, m)
      if ((k % 2) == 0) (t * t) % m else (((t * t) % m) * a) % m
    }
  }
}


import java.util.Scanner

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

  val Array(n, m, k) = scala.io.StdIn.readLine().split(" ").map(_.toLong)
  val A = scala.io.StdIn.readLine().split(" ").map(_.toLong)
  val B = scala.io.StdIn.readLine().split(" ").map(_.toLong)

  def solve() = {
    val cumulativeA = A.scan(0L)(_ + _)
    val cumulativeB = B.scan(0L)(_ + _)

    (0 to n.toInt).foldLeft(0) { (acc, i) =>
      if(cumulativeA(i) <= k) {
        var j = m.toInt
        while(cumulativeB(j) > k - cumulativeA(i))
          j -= 1
        Math.max(acc, i+j)
      } else acc
    }
  }

  println(solve())

}


object Main extends App {
  val Array(n, m, k) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
  val a = scala.io.StdIn.readLine.split(" ").map(_.toInt)
  val s = scala.io.StdIn.readLine.split(" ").map(_.toInt)

  var max = 0

  var a_sum: BigInt = 0
  (0 to a.length).foreach { i =>
    if (i != 0) {
      a_sum += a(i - 1)
    }
    if (a_sum > k) {
      println(max)
      sys.exit(0)
    }

    var s_sum: BigInt = 0
    import scala.util.control.Breaks
    val b = new Breaks
    b.breakable {
      (0 to s.length).foreach { j =>
        if (j != 0) {
          s_sum += s(j - 1)
        }
        if (a_sum + s_sum <= k) {
          //  println("i " + i + " :" + a_sum)
          //  println("j " + j + " :" + s_sum)
          max = List(max, i + j).max
        } else {
          b.break()
        }
      }
    }
  }

  println(max)
}


object Main extends App {
  val Array(n, m, k) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
  val a = scala.io.StdIn.readLine.split(" ").map(_.toInt)
  val s = scala.io.StdIn.readLine.split(" ").map(_.toInt)

  var max = 0

  var a_sum: BigInt = 0
  (0 to a.length).foreach { i =>
    if (i != 0) {
      a_sum += a(i - 1)
    }
    if (a_sum > k) {
      println(max)
      sys.exit(0)
    }

    var s_sum: BigInt = 0
    (0 to s.length).foreach { j =>
      if (j != 0) {
        s_sum += s(j - 1)
      }
      if (a_sum + s_sum <= k) {
        //  println("i " + i + " :" + a_sum)
        //  println("j " + j + " :" + s_sum)
        max = List(max, i + j).max
      }
    }
  }

  println(max)
}


import scala.math.max

object Scanner {
  private val buf = new Array[Byte](1024); private var ptr = 0; private var len = 0
  @inline private def isPrintableChar(c: Int): Boolean = 33 <= c && c <= 126
  @inline private def hasNextByte(): Boolean =
    if (ptr >= len) { ptr = 0; len = System.in.read(buf); len > 0 } else { true }
  @inline private def hasNext(): Boolean = {
    while (hasNextByte() && !isPrintableChar(buf(ptr))) ptr += 1
    hasNextByte()
  }
  @inline private def readByte(): Byte =
    if (hasNextByte()) { val res = buf(ptr); ptr += 1; res } else { -1 }
  def next(): String = {
    if(!hasNext()) ???
    val sb = new StringBuilder; var b = readByte()
    while (isPrintableChar(b)) { sb.append(b.toChar); b = readByte() }
    sb.toString
  }
  def nextInt(): Int = {
    val n = nextLong()
    if (n < Int.MinValue || Int.MaxValue < n) ???
    n.toInt
  }
  def nextLong(): Long = {
    if(!hasNext()) ???
    var minus = false; var b = readByte()
    if (b == '-') { minus = true; b = readByte() }
    def go (b: Byte, n: Long = 0): Long =
      if ('0' <= b && b <= '9') { go(readByte(), n * 10 + b - '0') }
      else if (minus) { -n } else { n }
    go(b)
  }
  def nextDouble(): Double = next.toDouble
}

object Main extends App{
  // val sc = Scanner
  val sc = new java.util.Scanner(System.in)
  val N, M, K = sc.nextInt
  val A = Array.fill(N)(sc.nextLong)
  val B = Array.fill(M)(sc.nextLong)
  var t: Long = A.sum
  var idx = N - 1
  var ans = 0
  var tmp = N
  for(i <- 0 to M){
    if(i != 0){
      t += B(i - 1)
      tmp += 1
    }
    while(t > K && idx >= 0){
      t -= A(idx)
      idx -= 1
      tmp -= 1
    }
    if(t <= K) ans = max(ans, tmp)
  }
  println(ans)
}


import scala.math.max

object Scanner {
  private val buf = new Array[Byte](1024); private var ptr = 0; private var len = 0
  @inline private def isPrintableChar(c: Int): Boolean = 33 <= c && c <= 126
  @inline private def hasNextByte(): Boolean =
    if (ptr >= len) { ptr = 0; len = System.in.read(buf); len > 0 } else { true }
  @inline private def hasNext(): Boolean = {
    while (hasNextByte() && !isPrintableChar(buf(ptr))) ptr += 1
    hasNextByte()
  }
  @inline private def readByte(): Byte =
    if (hasNextByte()) { val res = buf(ptr); ptr += 1; res } else { -1 }
  def next(): String = {
    if(!hasNext()) ???
    val sb = new StringBuilder; var b = readByte()
    while (isPrintableChar(b)) { sb.append(b.toChar); b = readByte() }
    sb.toString
  }
  def nextInt(): Int = {
    val n = nextLong()
    if (n < Int.MinValue || Int.MaxValue < n) ???
    n.toInt
  }
  def nextLong(): Long = {
    if(!hasNext()) ???
    var minus = false; var b = readByte()
    if (b == '-') { minus = true; b = readByte() }
    def go (b: Byte, n: Long = 0): Long =
      if ('0' <= b && b <= '9') { go(readByte(), n * 10 + b - '0') }
      else if (minus) { -n } else { n }
    go(b)
  }
  def nextDouble(): Double = next.toDouble
}

object Main extends App{
  val sc = Scanner
  val N, M, K = sc.nextInt
  val A = List.fill(N)(sc.nextInt)
  val B = List.fill(M)(sc.nextInt)
  var t: Long = 0
  var idx = -1
  for(i <- 0 until N){
    if(t + A(i) <= K){
      t += A(i)
      idx += 1
    }
  }
  var ans, tmp = idx + 1
  for(i <- 0 to M){
    if(i != 0){
      t += B(i - 1)
      tmp += 1
    }
    while(t > K && idx >= 0){
      t -= A(idx)
      idx -= 1
      tmp -= 1
    }
    if(t <= K) ans = max(ans, tmp)
  }
  println(ans)
}


import java.util.Scanner
import scala.math.max

object Main extends App{
  val sc = new Scanner(System.in)
  val N, M, K = sc.nextInt
  val A = List.fill(N)(sc.nextInt)
  val B = List.fill(M)(sc.nextInt)
  var t = A.sum
  var tmp = N
  var idx = N - 1
  var ans = 0
  for(i <- 0 to M){
    if(i != 0){
      t += B(i - 1)
      tmp += 1
    }
    while(t > K && idx >= 0){
      t -= A(idx)
      idx -= 1
      tmp -= 1
    }
    if(t <= K )ans = max(ans, tmp)
  }
  println(ans)
}


object Main extends App {
  val inputs: Seq[String] = scala.io.Source.stdin.getLines().toList
  val line1  = inputs.head.split(" ").map(_.toInt)
  val aBooks = inputs(1).split(" ").map(_.toInt)
  val bBooks = inputs(2).split(" ").map(_.toInt)

  println(solve(line1(0), line1(1), line1(2), aBooks, bBooks))

  def solve(n: Int, m: Int, k: Int, aBooks: Array[Int], bBooks: Array[Int]): Int = {
    val a = aBooks.foldLeft(Seq(0L))( (seq, v) => (seq.head + v) +: seq).reverse
    val b = bBooks.foldLeft(Seq(0L))( (seq, v) => (seq.head + v) +: seq).reverse

    var ans = 0
    var j   = m

    (0 until n + 1).foreach { i =>
      if(a(i) > k) {
        return ans
      }

      while(b(j) > k - a(i)) {
        j = j - 1
      }

      ans = Math.max(ans, i + j)
    }

    return ans
  }
}


object Main extends App {
	val pw = new java.io.PrintWriter(System.out)

	@scala.annotation.tailrec
	def loop(start: Int, end: Int)(f: Int => Unit): Unit =
		if (start < end) {
			f(start)
			loop(start + 1, end)(f)
		}

	val n, m = Scanner.nextInt
	val k = Scanner.nextLong

	val a = Array.fill(n)(Scanner.nextLong).scanLeft(0L)(_ + _)
	val b = Array.fill(m)(Scanner.nextLong).scanLeft(0L)(_ + _)

	pw.println(
		(0 to n).foldLeft((0, m)){ case ((max, j), i) =>
			if (a(i) > k) (max, j)
			else {
				val next = (j to 0 by -1).find(a(i) + b(_) <= k).getOrElse(0)
				(Math.max(max, i + next), next)
			}
		}._1
	)

	pw.flush()
}

object Scanner {
	private val buf = new Array[Byte](1024); private var ptr = 0; private var len = 0

	@inline private def isPrintableChar(c: Int): Boolean = 33 <= c && c <= 126
	@inline private def hasNextByte(): Boolean = if (ptr >= len) { ptr = 0; len = System.in.read(buf); len > 0 } else true
	@inline private def hasNext(): Boolean = {
		while (hasNextByte() && !isPrintableChar(buf(ptr))) ptr += 1
		hasNextByte()
	}
	@inline private def readByte(): Byte = if (hasNextByte()) { val res = buf(ptr); ptr += 1; res } else -1

	def next(): String = {
		if(!hasNext()) ???
		val sb = new StringBuilder; var b = readByte()
		while (isPrintableChar(b)) { sb.append(b.toChar); b = readByte() }
		sb.toString
	}

	def nextInt(): Int = {
		val n = nextLong()
		if (n < Int.MinValue || Int.MaxValue < n) ???
		n.toInt
	}

	def nextLong(): Long = {
		if(!hasNext()) ???
		var minus = false; var b = readByte()
		if (b == '-') { minus = true; b = readByte() }

		@scala.annotation.tailrec
		def go (b: Byte, n: Long = 0): Long = if ('0' <= b && b <= '9') go(readByte(), n * 10 + b - '0') else if (minus) -n else n

		go(b)
	}

	def nextDouble(): Double = next().toDouble
}


object Main extends App {
	val pw = new java.io.PrintWriter(System.out)

	@scala.annotation.tailrec
	def loop(start: Int, end: Int)(f: Int => Unit): Unit =
		if (start < end) {
			f(start)
			loop(start + 1, end)(f)
		}

	val n, m = Scanner.nextInt
	val k = Scanner.nextLong

	val a = Array.fill(n)(Scanner.nextLong).scanLeft(0L)(_ + _)
	val b = Array.fill(m)(Scanner.nextLong).scanLeft(0L)(_ + _)

	var ans = 0
	var j = m
	loop(0, n+1) { i =>
		if (a(i) <= k) {
			while (a(i) + b(j) > k) j -= 1
			ans = Math.max(ans, i + j)
		}
	}

	pw.println(ans)
	pw.flush()
}

object Scanner {
	private val buf = new Array[Byte](1024); private var ptr = 0; private var len = 0

	@inline private def isPrintableChar(c: Int): Boolean = 33 <= c && c <= 126
	@inline private def hasNextByte(): Boolean = if (ptr >= len) { ptr = 0; len = System.in.read(buf); len > 0 } else true
	@inline private def hasNext(): Boolean = {
		while (hasNextByte() && !isPrintableChar(buf(ptr))) ptr += 1
		hasNextByte()
	}
	@inline private def readByte(): Byte = if (hasNextByte()) { val res = buf(ptr); ptr += 1; res } else -1

	def next(): String = {
		if(!hasNext()) ???
		val sb = new StringBuilder; var b = readByte()
		while (isPrintableChar(b)) { sb.append(b.toChar); b = readByte() }
		sb.toString
	}

	def nextInt(): Int = {
		val n = nextLong()
		if (n < Int.MinValue || Int.MaxValue < n) ???
		n.toInt
	}

	def nextLong(): Long = {
		if(!hasNext()) ???
		var minus = false; var b = readByte()
		if (b == '-') { minus = true; b = readByte() }

		@scala.annotation.tailrec
		def go (b: Byte, n: Long = 0): Long = if ('0' <= b && b <= '9') go(readByte(), n * 10 + b - '0') else if (minus) -n else n

		go(b)
	}

	def nextDouble(): Double = next().toDouble
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val n, m, k = sc.nextInt
  val A = List.fill(n)(sc.nextInt)
  val B = List.fill(m)(sc.nextInt)

  val dA = maximum(A, k)
  val dB = maximum(B, k - dA.sum)

  val result = one(dA, dB)
  println(result)

  def maximum(desk: List[Int], sum: BigInt): List[Int] = {
    if (desk.map(BigInt(_)).sum <= sum) {
      desk
    } else {
      maximum(desk.init, sum)
    }
  }

  def one(deskA: List[Int], deskB: List[Int]): Int = {
    if (deskA.isEmpty) {
      deskB.length
    } else {
      val ifB = maximum(B, k - deskA.init.sum)
      if (ifB.length <= deskB.length || deskA.isEmpty) {
        deskA.length + deskB.length
      } else {
        one(deskA.init, ifB)
      }
    }
  }

}


object Main extends App {
  val nmk = scala.io.StdIn.readLine()
  val nmkArray = nmk.split(" ").map(_.toLong).toSeq
  val k = nmkArray(2)

  val a = scala.io.StdIn.readLine()
  val aArray = a.split(" ").map(_.toLong).toVector

  val b = scala.io.StdIn.readLine()
  val bArray = b.split(" ").map(_.toLong).toVector

  var resultVec = Vector.empty[Int]

  def calculate(aArrayInput: Vector[Long], bArrayInput: Vector[Long], timeCount: Long, resultTemp :Int): Unit = {
    if (aArrayInput.isEmpty && bArrayInput.isEmpty) {
      resultVec :+= resultTemp
    } else {
      if (timeCount > k) {
        resultVec :+= resultTemp
      } else {
        if (aArrayInput.isEmpty) {
          val newTimeCount = timeCount + bArrayInput.head
          val nextResult = if (newTimeCount > k) resultTemp else resultTemp + 1
          calculate(aArrayInput, bArrayInput.tail, newTimeCount, nextResult)
        } else if (bArrayInput.isEmpty) {
          val newTimeCount = timeCount + aArrayInput.head
          val nextResult = if (newTimeCount > k) resultTemp else resultTemp + 1
          calculate(aArrayInput.tail, bArrayInput, newTimeCount, nextResult)
        } else {
          val newTimeCountA = timeCount + aArrayInput.head
          val nextResultA = if (newTimeCountA > k) resultTemp else resultTemp + 1
          calculate(aArrayInput.tail, bArrayInput, newTimeCountA, nextResultA)

          val newTimeCountB = timeCount + bArrayInput.head
          val nextResultB = if (newTimeCountA > k) resultTemp else resultTemp + 1
          calculate(aArrayInput, bArrayInput.tail, newTimeCountB, nextResultB)
        }
      }
    }
  }

  calculate(aArray, bArray, 0L, 0)

  println(resultVec.max)
}


import scala.math

object Main extends App {
  val sc = new java.util.Scanner(System.in)
  var n , m , k = sc.nextInt()
  var a:List[Int] = List.fill(n)(sc.nextInt())
  var b:List[Int] = List.fill(m)(sc.nextInt())
  if (a.sum + b.sum <= k) {println(a.length + b.length);sys.exit()}
  a :+= 1000000000
  b :+= 1000000000
  var ans:BigInt = 0
  var co = 0
  var aa , bb = 0
  while (ans + math.min(a(aa),b(bb)) < k & co < n+m){
    ans = ans + math.min(a(aa),b(bb))
    if (a(aa) > b(bb)) {
      bb+=1
    } else {
      aa+=1
    }
    co += 1
  }
  println(co)
}


import scala.math

object Main extends App {
  val sc = new java.util.Scanner(System.in)
  var n , m , k = sc.nextInt()
  var a:List[Int] = List.fill(n)(sc.nextInt())
  var b:List[Int] = List.fill(m)(sc.nextInt())
  if (a.sum + b.sum <= k) {println(a.length + b.length);sys.exit()}
  a :+= 1000000000
  b :+= 1000000000
  var ans:BigInt = 0
  var co = 0
  while (ans + math.min(a(0),b(0)) < k & co < a.length + b.length){
    ans = ans + math.min(a(0),b(0))
    if (a(0) > b(0)) {
      b = b.drop(1)
    } else {
      a = a.drop(1)
    }
    co += 1
  }
  println(co)
}


object Main extends App {
	val pw = new java.io.PrintWriter(System.out)

	val n, m = Scanner.nextInt
	val k = Scanner.nextLong

	val a = Seq.fill(n)(Scanner.nextLong).scanLeft(0L)(_ + _)
	val b = Seq.fill(m)(Scanner.nextLong).scanLeft(0L)(_ + _)

	var ans = 0

	a.zipWithIndex foreach { case (as, ai) =>
		b.zipWithIndex foreach { case (bs, bi) =>
			if (as + bs <= k)
				ans = Math.max(ans, ai + bi)
		}
	}

	pw.println(ans)
	pw.flush()
}

object Scanner {
	private val buf = new Array[Byte](1024); private var ptr = 0; private var len = 0

	@inline private def isPrintableChar(c: Int): Boolean = 33 <= c && c <= 126
	@inline private def hasNextByte(): Boolean = if (ptr >= len) { ptr = 0; len = System.in.read(buf); len > 0 } else true
	@inline private def hasNext(): Boolean = {
		while (hasNextByte() && !isPrintableChar(buf(ptr))) ptr += 1
		hasNextByte()
	}
	@inline private def readByte(): Byte = if (hasNextByte()) { val res = buf(ptr); ptr += 1; res } else -1

	def next(): String = {
		if(!hasNext()) ???
		val sb = new StringBuilder; var b = readByte()
		while (isPrintableChar(b)) { sb.append(b.toChar); b = readByte() }
		sb.toString
	}

	def nextInt(): Int = {
		val n = nextLong()
		if (n < Int.MinValue || Int.MaxValue < n) ???
		n.toInt
	}

	def nextLong(): Long = {
		if(!hasNext()) ???
		var minus = false; var b = readByte()
		if (b == '-') { minus = true; b = readByte() }

		@scala.annotation.tailrec
		def go (b: Byte, n: Long = 0): Long = if ('0' <= b && b <= '9') go(readByte(), n * 10 + b - '0') else if (minus) -n else n

		go(b)
	}

	def nextDouble(): Double = next().toDouble
}


object methods {
  def solver(): Unit = {

    val tempList: Seq[Seq[String]] = {
      for (line <- io.Source.stdin.getLines()) yield {
        line.split(' ').toSeq
      }
    }.toSeq
    val N: Int = tempList(0)(0).toInt
    val M: Int = tempList(0)(1).toInt
    val K: Int = tempList(0)(2).toInt
    val ASeq: Seq[Int] = tempList(1).map(_.toInt)
    val BSeq: Seq[Int] = tempList(2).map(_.toInt)

    val reading: Int = readBook(ASeq, BSeq, K) //readNum = 0が初期値なので省略
    println(reading)
  }

  def readBook(bookA: Seq[Int], bookB: Seq[Int], K: Int, readNum: Int = 0): Int = {
    var timeLimit: Int = K
    var whichBook: String = "A"
    if (timeLimit < bookA.head && timeLimit < bookB.head) readNum
    else if(bookA.size == 0 && bookB.size == 0) readNum
    else if(bookA.size == 0){
      if(bookB.head <= timeLimit) {
        timeLimit -= bookB.head
        readBook(bookA, bookB.tail, timeLimit, readNum+1)
      } else readNum
    }
    else if(bookB.size == 0){
      if(bookA.head <= timeLimit) {
        timeLimit -= bookA.head
        readBook(bookA.tail, bookB, timeLimit, readNum+1)
      } else readNum
    }
    else {
      val changedBook: Seq[Int] = {
        if (bookA.head <= bookB.head) {
          timeLimit -= bookA.head
          whichBook = "A"
          bookA.tail
        } else {
          timeLimit -= bookB.head
          whichBook = "B"
          bookB.tail
        }
      }
      if(whichBook == "A") readBook(changedBook, bookB, timeLimit, readNum+1)
      else readBook(bookA, changedBook, timeLimit, readNum+1)
    } //else締め
  }
}

object Main extends App {
  methods.solver
}


import java.util.Scanner

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

  val Array(n, m, k) = scala.io.StdIn.readLine().split(" ").map(_.toLong)
  val A = scala.io.StdIn.readLine().split(" ").map(_.toLong)
  val B = scala.io.StdIn.readLine().split(" ").map(_.toLong)

  def solve(): Long = {
    readBook(A, B, 0, k)
  }

  def readBook(a: Array[Long], b: Array[Long], readCnt: Long, restMin: Long): Long = {
    if(restMin < 0 || (!canRead(a, restMin) && !canRead(b, restMin))) readCnt
    else {
      val readA = if(canRead(a, restMin)) readBook(a.drop(1), b, readCnt+1, restMin - a.head) else 0
      val readB = if(canRead(b, restMin)) readBook(a, b.drop(1), readCnt+1, restMin - b.head) else 0
      Math.max(readA, readB)
    }
  }

  def canRead(books: Array[Long], restMin: Long): Boolean = {
    if(books.isEmpty) false
    else books.head <= restMin
  }

  println(solve())

}


object Main extends App {
	val pw = new java.io.PrintWriter(System.out)

	@scala.annotation.tailrec
	def f(k: Long, a: Seq[Long], b: Seq[Long], count: Int = 0): Int =
		if (k < 0) count - 1
		else (a, b) match {
			case (Seq(), bhd :: btl) => f(k - bhd, Seq(), btl, count + 1)
			case (ahd :: atl, Seq()) => f(k - ahd, atl, Seq(), count + 1)
			case (ahd :: atl, bhd :: btl) =>
				if (ahd < bhd) f(k - ahd, atl, b, count + 1)
				else f(k - bhd, a, btl, count + 1)
			case _ => count
		}

	val n, m = Scanner.nextInt
	pw.println(f(Scanner.nextLong, Seq.fill(n)(Scanner.nextLong), Seq.fill(m)(Scanner.nextLong)))
	pw.flush()
}

object Scanner {
	private val buf = new Array[Byte](1024); private var ptr = 0; private var len = 0

	@inline private def isPrintableChar(c: Int): Boolean = 33 <= c && c <= 126
	@inline private def hasNextByte(): Boolean = if (ptr >= len) { ptr = 0; len = System.in.read(buf); len > 0 } else true
	@inline private def hasNext(): Boolean = {
		while (hasNextByte() && !isPrintableChar(buf(ptr))) ptr += 1
		hasNextByte()
	}
	@inline private def readByte(): Byte = if (hasNextByte()) { val res = buf(ptr); ptr += 1; res } else -1

	def next(): String = {
		if(!hasNext()) ???
		val sb = new StringBuilder; var b = readByte()
		while (isPrintableChar(b)) { sb.append(b.toChar); b = readByte() }
		sb.toString
	}

	def nextInt(): Int = {
		val n = nextLong()
		if (n < Int.MinValue || Int.MaxValue < n) ???
		n.toInt
	}

	def nextLong(): Long = {
		if(!hasNext()) ???
		var minus = false; var b = readByte()
		if (b == '-') { minus = true; b = readByte() }

		@scala.annotation.tailrec
		def go (b: Byte, n: Long = 0): Long = if ('0' <= b && b <= '9') go(readByte(), n * 10 + b - '0') else if (minus) -n else n

		go(b)
	}

	def nextDouble(): Double = next().toDouble
}


object Main extends App {
  /*
    import scala.collection.mutable

    val Array(n, m, k) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
    val a = scala.io.StdIn.readLine.split(" ").map(_.toInt)
    val s = scala.io.StdIn.readLine.split(" ").map(_.toInt)

    var memo = mutable.Set[(Int, Int)]()
    var max = 0
    var queue = new mutable.PriorityQueue[(BigInt, Int, Int)]()(Ordering.Tuple3[BigInt, Int, Int].reverse) // 消費時間,a,s

    queue.enqueue((0, -1, -1))

    while (queue.nonEmpty) {
      //  println(queue)
      val top = queue.dequeue()
      val time = top._1
      if (!memo((top._2, top._3))) {
        memo.add(top._2, top._3)
        max = List(max, top._2 + 1 + top._3 + 1).max

        if (top._2 < a.length - 1 && time + a(top._2 + 1) <= k) {
          queue.enqueue((time + a(top._2 + 1), top._2 + 1, top._3))
        }
        if (top._3 < s.length - 1 && time + s(top._3 + 1) <= k) {
          queue.enqueue((time + s(top._3 + 1), top._2, top._3 + 1))
        }
      }
    }

    println(max)
  */

  import scala.collection.mutable

  val Array(n, m, k) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
  val a = scala.io.StdIn.readLine.split(" ").map(_.toInt)
  val s = scala.io.StdIn.readLine.split(" ").map(_.toInt)

  var max = 0
  var queue = new mutable.Queue[(BigInt, Int, Int)]() // 消費時間,a,s
  var memo = Array.ofDim[Boolean](a.length + 2, s.length + 2)
  // println(memo.deep)

  queue.enqueue((0, 0, 0))

  while (queue.nonEmpty) {
    //  println(queue)
    val top = queue.dequeue()
    val time = top._1
    if (!memo(top._2)(top._3)) {
      memo(top._2)(top._3) = true
      max = List(max, top._2 + top._3).max

      if (top._2 < a.length && time + a(top._2) <= k) {
        queue.enqueue((time + a(top._2), top._2 + 1, top._3))
      }
      if (top._3 < s.length && time + s(top._3) <= k) {
        queue.enqueue((time + s(top._3), top._2, top._3 + 1))
      }
    }
  }

  println(max)

}


import scala.math

object Main extends App {
  val sc = new java.util.Scanner(System.in)
  var n , m , k = sc.nextInt()
  var a = Array.fill(n)(sc.nextInt())
  var b = Array.fill(m)(sc.nextInt())
  var ans = 0
  var co = 0
  while (ans + math.min(a(0),b(0)) < k & co < a.length + b.length){
    ans = ans + math.min(a(0),b(0))
    if (a(0) > b(0)) {b.drop(1) }else{ a.drop(1)}
    co += 1
  }
  println(co)
}


import scala.math

object Main extends App {
  val sc = new java.util.Scanner(System.in)
  var n , m , k = sc.nextInt()
  var a = Array.fill(n)(sc.nextInt())
  var b = Array.fill(m)(sc.nextInt())
  var ans = 0
  var co = 0
  while (ans + math.min(a(0),b(0)) < k & co <= a.length + b.length){
    ans = ans + math.min(a(0),b(0))
    if (a(0) > b(0)) {b.drop(1) }else{ a.drop(1)}
    co += 1
  }
  println(co)
}


object Main extends App {
  val nmk = scala.io.StdIn.readLine()
  val nmkArray = nmk.split(" ").map(_.toLong).toSeq
  val k = nmkArray(2)

  val a = scala.io.StdIn.readLine()
  val aArray = a.split(" ").map(_.toLong).toVector.sorted
  var aArrayTemp = aArray

  val b = scala.io.StdIn.readLine()
  val bArray = b.split(" ").map(_.toLong).toVector.sorted
  var bArrayTemp = bArray

  var result = 0
  var timeCount = 0L

  while (timeCount <= k) {
    val aMin = if (aArrayTemp.length > 0) Some(aArrayTemp.head) else None
    val bMin = if (bArrayTemp.length > 0) Some(bArrayTemp.head) else None
    if (aMin.isEmpty && bMin.isEmpty) {
      timeCount = k + 1L
    } else {
      val min = if (aMin.isEmpty) {
        bArrayTemp = bArrayTemp.tail
        bMin.get
      } else if (bMin.isEmpty) {
        aArrayTemp = aArrayTemp.tail
        aMin.get
      } else {
        if (aMin.get < bMin.get) {
          aArrayTemp = aArrayTemp.tail
          aMin.get
        } else {
          bArrayTemp = bArrayTemp.tail
          bMin.get
        }
      }
      timeCount = timeCount + min
      if (timeCount <= k) {
        result = result + 1
      }
    }
  }

  println(result)
}


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

    val n, m, k = nextInt
    val as = nextInts(n)
    val bs = nextLongs(m)
    val bSums = bs.scan(0L)(_ + _)

    @annotation.tailrec
    def binSearch(low: Long, hi: Long, limit: Long): Long = {
      if (hi < low) low
      else {
        val mid = (low + hi) / 2
        if (bSums(mid.toInt) > limit) binSearch(low, mid - 1, limit)
        else binSearch(mid + 1, hi, limit)
      }
    }
//println(bSums.mkString(" "))
    var max = 0L
    var aSum = 0L
    for (i <- as.indices) {
      aSum += as(i)
      if (aSum <= k) {
        var j = binSearch(0, m, k - aSum)
//        println(i, aSum, j, k - aSum)
//        if (j < m && bSums(j.toInt) > k - aSum) j -= 1
        val x = i + j
        if (x > max) {
          max = x
        }
      }
    }

    out.println(max)

    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 C {
object Main {
  import InOut._
  def main(args: Array[String]): Unit = {

    val n, m, k = nextInt
    val as = nextInts(n)
    val bs = nextLongs(m)
    val bSums = bs.scan(0L)(_ + _)

    @annotation.tailrec
    def binSearch(low: Long, hi: Long, limit: Long): Long = {
      if (hi < low) low
      else {
        val mid = (low + hi) / 2
        if (bSums(mid.toInt) >= limit) binSearch(low, mid - 1, limit)
        else binSearch(mid + 1, hi, limit)
      }
    }
//println(bSums.mkString(" "))
    var max = 0L
    var aSum = 0L
    for (i <- as.indices) {
      aSum += as(i)
      if (aSum <= k) {
        var j = binSearch(0, m, k - aSum)
//        println(i, aSum, j, k - aSum)
        if (j < m && bSums(j.toInt) > k - aSum) j -= 1
        val x = i + 1 + j
        if (x > max) {
          max = x
        }
      }
    }

    out.println(max)

    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
  }
}


import java.util.Scanner

object Main extends App {

  def readALine(c:Int, ac:List[Long]=Nil):List[Long] =
    if (c > 0) readALine(c-1, sc.nextLong::ac) else ac.reverse
  // def readLines(r:Int, c:Int, ac:List[List[Int]]):List[List[Int]] =
  //   if (r > 0) readLines(r-1, c, readALine(c, Nil)::ac) else ac.reverse
  val sc = new Scanner(System.in)
  val N = sc.nextInt

  def makePrime():(()=>Long, ()=>Unit) = {
    def eratosthenes(sieve:List[Long], primes:List[Long]):List[Long] = {
      if (sieve.isEmpty) primes.reverse
      else eratosthenes(sieve.tail.filter(_ % sieve.head != 0), sieve.head::primes)
    }
    val primes:Array[Long] = eratosthenes(List.range(3, 9999, 2), List(2)).toArray
    // println(primes.mkString(","))
    var num = 0
    val limit = primes.length
    (() => { if (num < limit) {num +=1; primes(num-1)} else throw new NoSuchElementException },
     () => { num = 0})
  }

  val (generator, resetGenerator) = makePrime()

  def factorize(n:Long):List[(Long, Long)] = {
    require(n > 0, "n must be a positive integer.")

    def iter(n:Long, ac:List[(Long, Long)]):List[(Long, Long)] = {
      def isDivided(n:Long, d:Long):Boolean = n % d == 0
      def iterDev(n:Long, d:Long, c:Long):(Long, Long) =
        if (isDivided(n, d)) iterDev(n/d, d, c+1) else (n, c)

      val div = generator()
      // println(s"n:$n ac:$ac div:$div")
      n match {
        case 1 => ac
        case n if n < div*div => (n, 1L)::ac
        case _ => {
          val (q, c) = iterDev(n, div, 0)
          if (c > 0) iter(q, (div, c)::ac) else iter(q, ac)
        }
      }
    }

    resetGenerator()
    iter(n, List()).reverse
  }

  def countDivisor(ls:List[(Long,Long)], count:Long):Long = {
    // println(s"ls:$ls count:$count")
    if (ls.isEmpty) count else {
      val (p, e) = ls.head
      countDivisor(ls.tail, count*(e+1))
    }
  }
  def solver(n:Long, sum:Long):Long =
    if (n > 0) solver(n -1, sum + n*countDivisor(factorize(n), 1)) else sum

  println(solver(N, 0))

}

Score : 400 points

Problem Statement

For a positive integer X, let f(X) be the number of positive divisors of X.

Given a positive integer N, find \sum_{K=1}^N K\times f(K).

Constraints

1 \leq N \leq 10^7

Input

Input is given from Standard Input in the following format:

N

Output

Print the value \sum_{K=1}^N K\times f(K).

Sample Input 1

4

Sample Output 1

23

We have f(1)=1, f(2)=2, f(3)=2, and f(4)=3, so the answer is 1\times 1 + 2\times 2 + 3\times 2 + 4\times 3 =23.

Sample Input 2

100

Sample Output 2

26879

Sample Input 3

10000000

Sample Output 3

838627288460105

Watch out for overflows.


object Main extends App {
    val stdin = new java.util.Scanner(new java.io.BufferedInputStream(System.in))
    val stdout = new java.io.PrintWriter(new java.io.BufferedOutputStream(System.out))

    while (stdin.hasNext()) {
        val foo = stdin.nextInt()
        var bar : Long = 0
        for (i <- 1 to foo) {
            val x : Long = i
            val k : Long = foo / x
            bar += (x + x * k) * k / 2
        }
        stdout.printf("%d\n", bar.asInstanceOf[java.lang.Long])
    }

    stdin.close()
    stdout.close()
}


import java.util.Scanner

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

  val n = scala.io.StdIn.readInt()

  def solve(): Long = {
    (1 to n).foldLeft(0L) { (acc, num) =>
      acc + num * sumToN(n/num)
    }
  }

  def sumToN(n: Long): Long = n * (n + 1) / 2

  println(solve())

}


object Main extends App {
  val inputs: Seq[String] = scala.io.Source.stdin.getLines().toList
  val n = inputs.head.toInt

  println(solve(n))

  def solve(n: Int): Long = {
    val nums = scala.collection.mutable.ArrayBuffer.fill(n+1)(0)
    var ans = 0L

    (1 to n).foreach { i =>
      (1 to i).foreach { j =>
        if (i % j == 0) ans = ans + i
      }
    }
    return ans
  }
}


object Main extends App {
  val inputs: Seq[String] = scala.io.Source.stdin.getLines().toList
  val n = inputs.head.toInt

  println(solve(n))

  def solve(n: Int): Long = {
    val nums = scala.collection.mutable.ArrayBuffer.fill(n+1)(0)
    var ans = 0L

    (1 to n).foreach { i =>
      (1 to i).foreach { j =>
        if (i % j == 0) nums.update(i, nums(i) + 1)
      }
    }

    (1 to n).foreach { i =>
      ans = ans + nums(i) * i
    }
    return ans
  }
}


// time out
object Main extends App {
  val inputs: Seq[String] = scala.io.Source.stdin.getLines().toList
  val n = inputs.head.toInt

  println(solve(n))

  def solve(n: Int): Long = {
    var ans = 0L
    (1 to n).foreach { i =>
      (1 to n).foreach { j =>
        if (i % j == 0) ans = ans + i
      }
    }

    return ans
  }
}


object Main extends App {
	val pw = new java.io.PrintWriter(System.out)

	val n = Scanner.nextInt

	def g(x: Long): Long = {
		val y = n / x
		y * (y + 1) * x / 2
	}

	pw.println((1 to n).foldLeft(0L){case (acc, j) => acc + g(j)})
	pw.flush()
}

object Scanner {
	private val buf = new Array[Byte](1024); private var ptr = 0; private var len = 0

	@inline private def isPrintableChar(c: Int): Boolean = 33 <= c && c <= 126
	@inline private def hasNextByte(): Boolean = if (ptr >= len) { ptr = 0; len = System.in.read(buf); len > 0 } else true
	@inline private def hasNext(): Boolean = {
		while (hasNextByte() && !isPrintableChar(buf(ptr))) ptr += 1
		hasNextByte()
	}
	@inline private def readByte(): Byte = if (hasNextByte()) { val res = buf(ptr); ptr += 1; res } else -1

	def next(): String = {
		if(!hasNext()) ???
		val sb = new StringBuilder; var b = readByte()
		while (isPrintableChar(b)) { sb.append(b.toChar); b = readByte() }
		sb.toString
	}

	def nextInt(): Int = {
		val n = nextLong()
		if (n < Int.MinValue || Int.MaxValue < n) ???
		n.toInt
	}

	def nextLong(): Long = {
		if(!hasNext()) ???
		var minus = false; var b = readByte()
		if (b == '-') { minus = true; b = readByte() }

		@scala.annotation.tailrec
		def go (b: Byte, n: Long = 0): Long = if ('0' <= b && b <= '9') go(readByte(), n * 10 + b - '0') else if (minus) -n else n

		go(b)
	}

	def nextDouble(): Double = next().toDouble
}


import java.io.{BufferedOutputStream, BufferedReader, InputStreamReader, PrintWriter}
import java.lang

import scala.annotation.tailrec
import scala.collection.mutable.ArrayBuffer
import scala.reflect.ClassTag

object Main {
  def get[T: ClassTag](implicit in: BufferedReader, converter: String => T): T = {
    converter(in.readLine)
  }

  def getArray[T: ClassTag](implicit in: BufferedReader, converter: String => T): Array[T] = {
    get[String].split("\\s+").map[T](converter)
  }

  implicit val idConverter: String => String = s => s
  implicit val intConverter: String => Int = s => Integer.parseInt(s)
  implicit val longConverter: String => Long = s => lang.Long.parseLong(s)

  def get[T1, T2](
                   implicit in: BufferedReader,
                   converter1: String => T1,
                   converter2: String => T2
                 ): (T1, T2) = {
    getArray[String] match {
      case Array(v1, v2) => (converter1(v1), converter2(v2))
    }
  }

  def get[T1, T2, T3](
                       implicit in: BufferedReader,
                       converter1: String => T1,
                       converter2: String => T2,
                       converter3: String => T3
                     ): (T1, T2, T3) = {
    getArray[String] match {
      case Array(v1, v2, v3) => (converter1(v1), converter2(v2), converter3(v3))
    }
  }

  def get[T1, T2, T3, T4](
                           implicit in: BufferedReader,
                           converter1: String => T1,
                           converter2: String => T2,
                           converter3: String => T3,
                           converter4: String => T4
                         ): (T1, T2, T3, T4) = {
    getArray[String] match {
      case Array(v1, v2, v3, v4) => (converter1(v1), converter2(v2), converter3(v3), converter4(v4))
    }
  }

  implicit class TimesInt(val n: Int) {
    def times(f: Int => Unit): Unit = {
      for (i <- 0 until n) {
        f(i)
      }
    }
  }

  def primes(n: Long): ArrayBuffer[Long] = {
    val buf = ArrayBuffer.empty[Long]
    val s = Math.sqrt(n).toInt

    var v = n
    for (i <- 2 to s) {
      if (v == 1 || v == 0) {
        return buf
      } else {
        while (v % i == 0) {
          buf.append(i)
          v /= i
        }
      }
    }
    if (v > s) {
      buf.append(v)
    }
    buf
  }

  def divisors(n: Int): ArrayBuffer[Int] = {
    val buf = ArrayBuffer.empty[Int]
    val s = Math.sqrt(n).toInt

    for (i <- 1 to s) {
      if (n % i == 0) {
        buf.append(i)
        if (i != n / i) {
          buf.append(n / i)
        }
      }
    }
    buf
  }

  @tailrec
  def gcd(a: Long, b: Long): Long = {
    val reminder = a % b
    if (reminder == 0) {
      b
    } else {
      gcd(b, reminder)
    }
  }

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

  def toBitArray(n: Int, width: Int): Array[Boolean] = {
    val buf = ArrayBuffer.fill(width)(false)

    @tailrec
    def inner(n: Int, i: Int): Array[Boolean] = {
      buf(i) = (n & 1) == 0
      if (i == 0) {
        buf.toArray
      } else {
        inner(n / 2, i - 1)
      }
    }

    inner(n, width - 1)
  }

  def modpow(n: Long, p: Long, m: Long): Long = {
    @tailrec
    def inner(n: Long, p: Long, acc: Long): Long = {
      if (p == 0) {
        acc
      } else if ((p & 1) == 0) {
        inner(n * n % m, p >> 1, acc)
      } else {
        inner(n * n % m, p >> 1, acc * n % m)
      }
    }

    inner(n % m, p, 1)
  }

  def main(args: Array[String]): Unit = {
    implicit val in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    val out = new PrintWriter(new BufferedOutputStream(System.out))
    val n = get[Int]

    var sum = BigInt(0)
    for (i <- 1 to n) {
      val max = BigInt(n / i * i)
      sum += (max + i) * (n / i) / 2
    }
    out.println(sum)
    out.flush()
  }
}


import java.util.Scanner;

object Main extends App {

  val sc = new Scanner(System.in);

  val n = sc.nextInt();
  val as = Array.fill(n)(sc.nextInt());
  val ab = Array.fill(n)(false);

  var i1: Int = 0;

  while (i1 < n) {
    var i2: Int = i1 + 1;
    while (i2 < n) {
      if (as(i1) % as(i2) == 0) {
        ab(i1) = true;
      }
      if (as(i2) % as(i1) == 0) {
        ab(i2) = true;
      }
      i2 = i2 + 1;
    }
    i1 = i1 + 1;
  }

  val answer = n - ab.count(f => f);
  println(answer);

}

Score : 400 points

Problem Statement

Given is a number sequence A of length N.

Find the number of integers i \left(1 \leq i \leq N\right) with the following property:

For every integer j \left(1 \leq j \leq N\right) such that i \neq j , A_j does not divide A_i.

Constraints

All values in input are integers.

1 \leq N \leq 2 \times 10^5

1 \leq A_i \leq 10^6

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \cdots A_N

Output

Print the answer.

Sample Input 1

5
24 11 8 3 16

Sample Output 1

3

The integers with the property are 2, 3, and 4.

Sample Input 2

4
5 5 5 5

Sample Output 2

0

Note that there can be multiple equal numbers.

Sample Input 3

10
33 18 45 28 8 19 89 86 2 4

Sample Output 3

5


import java.util.Scanner;

object Main extends App {

  val sc = new Scanner(System.in);

  val n = sc.nextInt();
  val as = List.fill(n)(sc.nextInt());

  @scala.annotation.tailrec
  def sub(as1: List[Int], as2: List[Int]): List[Int] = {
    as1 match {
      case Nil => as2;
      case h :: t =>
        val p = t.indexWhere(_ > h);
        if (p == 0) {
          val as1_1 = t.filter(_ % h != 0);
          sub(as1_1, h :: as2);
        } else if (p > 0) {
          val as1_1 = t.drop(p).filter(_ % h != 0);
          sub(as1_1, as2);
        } else {
          if (t.isEmpty) {
            h :: as2;
          } else {
            as2;
          }
        }
    }
  }

  println(sub(as.sorted, Nil).size);
}


import java.util.Scanner;

object Main extends App {

  val sc = new Scanner(System.in);

  val n = sc.nextInt();
  val as = List.fill(n)(sc.nextInt());

  @scala.annotation.tailrec
  def sub(as1: List[Int], as2: List[Int]): List[Int] = {
    as1 match {
      case Nil => as2;
      case h :: t =>
        val (as1_1, as1_2) = t.partition(_ % h != 0);
        val as2_1 = as2.filter(_ % h != 0);
        if (as1_2.exists(_ == h)) {
          sub(as1_1, as2_1);
        } else {n
          sub(as1_1, h :: as2_1);
        }
    }
  }

  println(sub(as.sorted, Nil).size);
}


import java.util.Scanner

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

  def read(): (Int, Array[Int]) = {
    val sc: Scanner = new Scanner(System.in)
    val n = sc.nextInt()
    val arr = Array.fill(n)(sc.nextInt)
    sc.close()
    (n, arr)
  }

  def solve(): Int = {
    val (_, arr) = read()
    val sorted = arr.sorted
    val len = sorted.length
    val maxLen = Math.max(len, sorted(len-1)) + 1
    val cntArr = Array.fill(maxLen)(0)

    sorted.foreach { num =>
      if(cntArr(num) != 0) cntArr(num) = 2
      else (num until maxLen by num).foreach(cntArr(_) += 1)
    }
    sorted.foldLeft(0) { (cnt, num) =>
      if(cntArr(num) == 1) cnt+1 else cnt
    }
  }

  println(solve())

}


import java.util.Scanner

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

  def read(): (Int, Array[Int]) = {
    val sc: Scanner = new Scanner(System.in)
    val n = sc.nextInt()
    val arr = Array.fill(n)(sc.nextInt)
    sc.close()
    (n, arr)
  }

  def solve(): Int = {
    val (_, arr) = read()
    val sorted = arr.sorted
    val len = sorted.length
    val canDivideArr = Array.fill(len)(false)

    def markDivideNum(i: Int, nums: Array[Int], len: Int): Unit = {
      (i until len).foreach { index =>
        if(nums(index) % nums(i) == 0) canDivideArr(index) = true
      }
    }

    (0 until len).foldLeft(0) { case (acc, index) =>
      if(canDivideArr(index)) acc
      else {
        markDivideNum(index, sorted, len)
        if(len >= 2 && sorted.head == sorted(1)) acc else acc + 1
      }
    }
  }

  println(solve())

}


import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

object methods {
  def solver(): Unit = {

    val tempList: Seq[Seq[String]] = {
      for (line <- io.Source.stdin.getLines()) yield {
        line.split(' ').toSeq
      }
    }.toSeq
    val N: Int = tempList(0)(0).toInt
    val numList: Seq[Int] = tempList(1).map(_.toInt)

    println(harmonySeries(numList, N))
  }

   //調和級数を用いた解法
  def harmonySeries(numList: Seq[Int], N: Int): Int = {
    val rangeMax: Int = numList.max + 1
    val numMax: Int = numList.max
    val buffer: ArrayBuffer[Int] = mutable.ArrayBuffer.fill(rangeMax)(0)

    //記録
    numList.distinct.foreach {x =>
      //x.to(numMax).by(x).toList.foreach(v => if(buffer(v) <= 1) buffer(v) += 1)
      for(v <- x.to(numMax).by(x)){if(buffer(v) <= 1) buffer(v) += 1}
    }

    //値が1のインデックスを集計：リスト内の割り切れない数or割り切れない数の倍数
    val includeMultipleIndexSet: Set[Int] = buffer.zipWithIndex.filter(x => x._1 == 1).map(x => x._2).toSet
    val indexSet: Set[Int] = includeMultipleIndexSet.intersect(numList.toSet)
    //重複数字の集合を作りたい
    val duplicateNum: Set[Int] = numList.groupBy(identity).mapValues(_.size).map{
      case (key, value) => {
        if(value >= 2) key
        else 0
      }
    }.toSet

    val indivisibleList: List[Int] = indexSet.diff(duplicateNum).toList
    indivisibleList.length
  }
}

object Main extends App {
  methods.solver()
}


import scala.io.StdIn._

object Main extends App {
  private val MAX = 1_000_000

  val n = readInt
  val A = readLine.split(" ").map(_.toInt)
  val v = Array.fill(MAX + 10)(0)

  A.foreach { Ai =>
    if (v(Ai) > 0) {
      v(Ai) = 2
    } else {
      for (step <- Ai to MAX by Ai) {
        v(step) += 1
      }
    }
  }

  val ans = A.count { Ai => v(Ai) == 1 }
  println(ans)
}


import scala.io.StdIn._

object Main extends App {
  private val MAX = 2 * 100000

  val n = readInt
  val a = readLine.split(" ").map(_.toInt)

  val v = Array.fill(MAX + 5)(0)

  a.foreach { ai =>
    Range.inclusive(1, MAX / ai).foreach { t =>
      v(ai * t) = v(ai * t) + 1
    }
  }

  val ans = a.count { ai => v(ai) == 1 }
  println(ans)
}


import scala.io.StdIn._

object Main extends App {
  val n = readInt
  val a = readLine.split(" ").map(_.toInt).sorted

  val ans = Range(0, n).count { i =>
    def divisibleOnLeft = Range(0, i).exists { j =>
      a(i) % a(j) == 0
    }
    def nextValueEqual = i < n - 1 && a(i) == a(i + 1)

    !divisibleOnLeft && !nextValueEqual
  }

  println(ans)
}


object methods {
  def solver(): Unit = {

    val tempList: Seq[Seq[String]] = {
      for (line <- io.Source.stdin.getLines()) yield {
        line.split(' ').toSeq
      }
    }.toSeq
    val N: Int = tempList(0)(0).toInt
    val numList: Seq[Int] = tempList(1).map(_.toInt)

    //一旦愚直にやってみるO(N*(N-1))
    var allCounter: Int = 0
    numList.zipWithIndex.foreach{v =>
      var i: Int = 0
      var counter: Int = 0
      while(i < N){//iが自分自身のインデックス以外で、割り切れなかったとき
        if(i != v._2 && v._1 % numList(i) != 0) counter += 1
        //任意の値で割り切れなかったとき、counterはN-1になるはず
        if(counter == N-1) allCounter += 1
        i += 1
      }
    }

    println(allCounter)
  }
}

object Main extends App {
  methods.solver()
}


object Main extends App {
  val in = new java.util.Scanner(System.in)
  val N = in.nextInt
  val As = List.fill(N)(in.nextInt).sorted
  val dividable = new Array[Boolean](1_000_001)

  def count(l: List[Int], c: Int): Int = l match {
    case Nil => c
    case x :: xs =>
      if (dividable(x)) count(xs, c)
      else {
        (x to 1_000_001 by x).foreach {i => dividable(i) = true}
        count(xs, c + (if (xs.headOption == Some(x)) 0 else 1))
      }
  }

  println(count(As, 0))
}


import java.util.Scanner

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

object Main {

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

    val n = sc.nextInt()
    val a = Array.fill(n)(sc.nextInt())
    val aset = a.toSet

    if (aset.contains(1)) {
      println(0)
    } else {
      var cnt = 0
      aset.foreach { i =>
        val idiv = divisors(i)
        if (!idiv.exists(aset.contains)) cnt += 1
      }

      val arr = ArrayBuffer.fill(1000005)(0)
      a.foreach { i =>
        val k = arr(i - 1)
        if (k == 1) {
          cnt -= 1
          arr(i - 1) += 1
        } else {
          arr(i - 1) += 1
        }
      }

      println(cnt)

    }
  }

  def divisors(n: Int): ArrayBuffer[Int] = {
    val ld = mutable.ArrayBuffer.empty[Int]
    val ud = mutable.ArrayBuffer.empty[Int]
    var i = 2
    while (i * i <= n) {
      if (n % i == 0) {
        ld += i
        if (i != n / i) {
          ud += n / i
        }
      }
      i += 1
    }
    ld ++ ud
  }

}


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

object Main extends App with StdInHelper {
  val n = readInt
  val as = readInts

  val maxA = as.max
  val dp = scala.collection.mutable.Map[Int, Int]().withDefaultValue(0)

  for (a <- as) {
    for (i <- a to maxA by a) {
      dp(i) += 1
    }
  }

  var res = 0

  for (a <- as) {
    if (dp(a) == 1) res += 1
  }

  println(res)
}

trait StdInHelper {
  def readStrings = {
    val l = readLine
    if (l == "") Array.empty[String]
    else l.split(" ")
  }
  def readInts = readStrings.map(_.toInt)
  def readLongs = readStrings.map(_.toLong)
  def readDoubles = readStrings.map(_.toDouble)
  def readBigInts = readStrings.map(BigInt.apply(_))
  def readBigDecimals = readStrings.map(BigDecimal.apply(_))
}


object Main extends App {
  val inputs: IndexedSeq[String] = scala.io.Source.stdin.getLines().toIndexedSeq

  val n = inputs(0).toInt
  val nums = inputs(1).split(" ").map(_.toInt)

  println(solve(n, nums))

  def solve(n: Int, nums: IndexedSeq[Int]): Int = {
    val sortedNums = nums.sorted
    var divSeq = sortedNums
    val results = scala.collection.mutable.IndexedSeq.fill(n)(true)

    (0 until n).foreach { i =>
      // 約分されたものはスキップ
      if(results(i)) {
        // 分母
        val div = divSeq(i)

        (i + 1 until n).foreach { j =>
          // 約分されたものはスキップ
          if(results(j)) {
            // 割り切れる人たち
            if (sortedNums(j) % div == 0) {
              results.update(j, false)
            }

            // 同じ数値を持つものは消す.
            if (sortedNums(i) == sortedNums(j)) {
              results.update(i, false)
            }
          }
        }
      }
    }

    var result = 0
    results.foreach { v =>
      if (v) {
        result = result + 1
      }
    }

    return result
  }
}


object Main extends App {
  val inputs: IndexedSeq[String] = scala.io.Source.stdin.getLines().toIndexedSeq

  val n = inputs(0).toInt
  val nums = inputs(1).split(" ").map(_.toInt)

  println(solve(n, nums))

  def solve(n: Int, nums: IndexedSeq[Int]): Int = {
    val sortedNums = nums.sorted
    val max = sortedNums(sortedNums.size - 1)
    var divSeq = sortedNums
    // 不要な配列が増えるが、添字で直接処理できるように入力の最大値分のデータを用意
    val results = scala.collection.mutable.IndexedSeq.fill(max + 1)(0)

    (1 to n).foreach { i =>
      // 分母
      val div = divSeq(i-1)

      // <= 1にしてelseなしでも良い
      if(results(div) == 0) {
        Range.inclusive(div, max, div).foreach { j =>
          results.update(j, results(j) + 1)
        }
      } else {
        results.update(div, 2)
      }
    }

    // 入力に関係ない範囲を無視するためにsortedNumsのデータでアクセスしてチェック
    var result = 0
    sortedNums.foreach { v =>
      if (results(v) == 1) {
        result = result + 1
      }
    }
    return result
  }
}


import java.security.KeyStore.TrustedCertificateEntry
import java.util
import java.util.regex.Pattern
import java.util.{ArrayList, Collections, Comparator, List => JList}

import scala.collection.immutable.TreeMap
import scala.math._
import scala.collection.mutable
import scala.collection.mutable.{ArrayBuffer, ListBuffer}
import scala.util.{Failure, Success, Try}

object Main{
  val LINE_SEPARATOR = "\n"
  def main(args: Array[String]): Unit = {
    if (sys.env.getOrElse("TEST", "")=="1"){
      println(test());
    }else{
      val input=io.Source.stdin.getLines().mkString(LINE_SEPARATOR);
      println(solve(input).trim());
    }
  }

  def init (nRows: Int, nCols: Int, default: Int) = Array.tabulate(nRows,nCols)( (x,y) =>  default)

  def sortIgnoreCase1(list: JList[String]): JList[String] = {
    val r = new ArrayList[String](list)
    Collections.sort(r, new Comparator[String] {
      override def compare(o1: String, o2: String): Int = o1.compareToIgnoreCase(o2)
    })
    r
  }

  def solve(input: String): String = {
    val n = input.split(LINE_SEPARATOR).head.toInt
    val a = input.split(LINE_SEPARATOR).tail.head.split(" ").map(_.toInt).sorted
    val res = (0 to pow(10, 6).toInt).map(_ => 0).toArray
    a.foreach{ai =>
      if (res(ai) == 0) {
        (ai to pow(10, 6).toInt by ai).foreach{aix =>
          res(aix) += 1
        }
      } else {
        res(ai) += 1
      }
    }
    a.map(res(_) == 1).count(b => b).toString
  }

  def medianCalculator(seq: Seq[Long]): Long = {
    //In order if you are not sure that 'seq' is sorted
    val sortedSeq = seq.sortWith(_ < _)

    if (seq.size % 2 == 1) sortedSeq(sortedSeq.size / 2)
    else {
      val (up, down) = sortedSeq.splitAt(seq.size / 2)
      (up.last + down.head) / 2
    }
  }

  def factorize(x: Long): List[Long] = {
    def foo(x: Long, a: Long = 2, list: List[Long] = Nil): List[Long] = a*a > x match {
      case false if x % a == 0 => foo(x / a, a    , a :: list)
      case false               => foo(x    , a + 1, list)
      case true                => x :: list
    }
    foo(x)
  }

  def divisors(n: Int): Vector[Int] = {
    val halfList = (1 to sqrt(n).toInt).toVector.filter(n % _ == 0).map(_.toInt)
    val reversedList = if (sqrt(n).floor == sqrt(n)) halfList.reverse.tail.map(n/_) else halfList.reverse.map(n/_)
    halfList ++ reversedList
  }

  def gcd(m: Long, n: Long): Long = n match {
    case 0 => m
    case _ => gcd(n, m % n)
  }
  def lcm(a: Long, b: Long): Long = a * b / gcd(a, b)

  val tests=List(
    """5
      |24 11 8 3 16""".stripMargin -> """3
                                            |
                                          |
                               |
                                     |
                                   |
                                 |""".stripMargin
    ,
    """4
      |5 5 5 5""".stripMargin -> """0
                                       |
                                          |
                                 |""".stripMargin,
    """10
      |33 18 45 28 8 19 89 86 2 4""".stripMargin -> """5
                                |""".stripMargin
  )

  def test():String= {
    return tests.map{case (i,o)=>(i.trim(),o.trim())}
      .zipWithIndex.map{
      case ((input,outputExpect),i)=>{
        val output=solve(input).trim();
        s"test${i+1}:"+(if(output==outputExpect){
          "Passed"
        }else{
          s"Failed\nexpect:\n${outputExpect}\noutput:\n${output}"
        })
      }}
      .mkString("\n");
  }
}


object Main extends App {
  val inputs: Seq[String] = scala.io.Source.stdin.getLines().toList
  // val inputs = Seq("4", "5 5 5 5")
  // val inputs = Seq("10", "33 18 45 28 8 19 89 86 2 4")

  val n = inputs(0).toInt
  val nums = inputs(1).split(" ").map(_.toInt)
  // val inputs = Seq("100 0", "")
  println(solve(n, nums))

  def solve(n: Int, nums: Seq[Int]): Int = {
    val sortedNums = nums.sorted
    var divSeq = sortedNums
    val results = scala.collection.mutable.Seq.fill(n)(true)

    (0 until n).foreach { i =>
      // 約分されたものはスキップ
      if(results(i)) {
        val div = divSeq(i)
        (i + 1 until n).foreach { j =>
          if (sortedNums(j) % div == 0) {
            results.update(j, false)
          }

          if (sortedNums(i) == sortedNums(j)) {
            results.update(i, false)
          }
        }

        if(divSeq.tail.isEmpty) {
          return results.filter(v => v).size
        }
      }
    }

    return results.filter(v => v).size
  }
}


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

object Main extends App with StdInHelper {
  val n = readInt
  val as = readInts.groupBy(i => i)

  var res = 0

  for (i <- as.filter(m => m._2.length == 1).map(_._1).toSeq.sorted) {
    val b = new scala.util.control.Breaks
    b.breakable {
      for (j <- as.map(_._1).toSeq.sorted) {
        if (as.get(i).head.head < as.get(j).head.head) {
          res += 1
          b.break
        }
        if (i != j &&
            as.get(i).head.head % as.get(j).head.head == 0 &&
            as.get(i).head.head >= as.get(j).head.head) {
          b.break
        }
      }
      res += 1
    }
  }
  println(res)
}

trait StdInHelper {
  def readStrings = {
    val l = readLine
    if (l == "") Array.empty[String]
    else l.split(" ")
  }
  def readInts = readStrings.map(_.toInt)
  def readLongs = readStrings.map(_.toLong)
  def readDoubles = readStrings.map(_.toDouble)
  def readBigInts = readStrings.map(BigInt.apply(_))
  def readBigDecimals = readStrings.map(BigDecimal.apply(_))
}


object Main {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn.readLine
    val Array(datN) = readLine.split(" ").map(_.toInt)
    val datA = readLine.split(" ").map(_.toInt).sorted

    def removeMultiplied(res: Array[Int], i: Int, dat: Array[Int]): Array[Int] = {
      if (dat.isEmpty) res
      else {
        val res_ = if (dat.head % i != 0) res ++ Array(dat.head) else res
        removeMultiplied (res_, i, dat.tail)
      }
    }
    def countAns(res: Int, dat: Array[Int]): Int = {
      if (dat.isEmpty) res
      else {
        val res_ = if((dat.length >= 2) && (dat(0) == dat(1))) res else res + 1
        //countAns(res_, removeMultiplied(Array(), dat.head, dat.tail))
        countAns(res_, dat.tail.filter(a => a % dat.head != 0))
      }
    }
    val ans = countAns(0, datA)
    println(ans)
  }
}


import scala.util.control.Breaks

object Main extends App {
  val n = scala.io.StdIn.readInt()
  val aInput = scala.io.StdIn.readLine()
  val aArray =  aInput.split(" ").map(_.toInt).toVector.sorted

  var result = 0

  aArray.zipWithIndex.foreach { a =>
    val b = new Breaks
    b.breakable {
      (0 to n - 1).foreach { i =>
        if (a._2 != i) {
          val bunbo = aArray(i)
          if (a._1 < bunbo) {
            b.break()
          } else if (a._1 % bunbo == 0) {
            result = result + 1
            b.break()
          } else if (a._1 / 2 + 1 < bunbo) {
            b.break()
          }
        }
      }
    }
  }
  println(n - result)

}


object Main {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn.readLine
    val Array(datN) = readLine.split(" ").map(_.toInt)
    val datA = readLine.split(" ").map(_.toInt).sorted

    def removeMultiplied(res: Array[Int], i: Int, dat: Array[Int]): Array[Int] = {
      if (dat.isEmpty) res
      else {
        val res_ = if (dat.head % i != 0) res ++ Array(dat.head) else res
        removeMultiplied (res_, i, dat.tail)
      }
    }
    def countAns(res: Int, dat: Array[Int]): Int = {
      if (dat.isEmpty) res
      else {
        val res_ = if((dat.length >= 2) && (dat(0) == dat(1))) res else res + 1
        countAns(res_, removeMultiplied(Array(), dat.head, dat.tail))
      }
    }
    val ans = countAns(0, datA)
    println(ans)
  }
}


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

object Main extends App with StdInHelper {
  val n = readInt
  val as = readInts.sorted

  var res = 0

  for (i <- 0 to as.length - 1) {
    val b = new scala.util.control.Breaks
    b.breakable {
      for (j <- 0 to as.length - 1) {
        if (as(i) < as(j)) {
          res += 1
          b.break
        }
        if (i != j && as(i) % as(j) == 0 && as(i) >= as(j)) {
          b.break
        }
      }
      res += 1
    }
  }
  println(res)
}

trait StdInHelper {
  def readStrings = {
    val l = readLine
    if (l == "") Array.empty[String]
    else l.split(" ")
  }
  def readInts = readStrings.map(_.toInt)
  def readLongs = readStrings.map(_.toLong)
  def readDoubles = readStrings.map(_.toDouble)
  def readBigInts = readStrings.map(BigInt.apply(_))
  def readBigDecimals = readStrings.map(BigDecimal.apply(_))
}


import scala.annotation.tailrec

object Main extends App {
  val sc = new Scanner
  val N = sc.nextInt
  val As = Vector.fill(N)(sc.nextInt).sorted

  @tailrec def loop(done: Seq[Int], queue: Seq[Int], count: Int): Int = queue match {
    case first +: second +: rest =>
      if (done.exists(first % _ == 0)) {
        loop(done, second +: rest, count)
      } else if (second == first) {
        loop(first +: done, second +: rest, count)
      } else {
        loop(first +: done, second +: rest, count + 1)
      }
    case first +: rest =>
      if (done.exists(first % _ == 0)) {
        loop(done, rest, count)
      } else {
        loop(first +: done, rest, count + 1)
      }
    case _ => count
  }

  val ans = loop(Seq.empty[Int], As, 0)
  println(ans)
}

// https://qiita.com/p_shiki37/items/a0f6aac33bf60f5f65e4
object Scanner {
  private def isPrintableChar(c: Int) = 33 <= c && c <= 126
}

class Scanner {
  private[this] val in = System.in
  private[this] val buffer = new Array[Byte](1024)
  private[this] var ptr = 0
  private[this] var buflen = 0

  private def hasNextByte: Boolean =
    if (ptr < buflen) true
    else {
      ptr = 0
      buflen = in.read(buffer)
      buflen > 0
    }

  private def readByte: Byte =
    if (hasNextByte) {
      ptr += 1
      buffer(ptr - 1)
    } else -1

  def hasNext: Boolean = {
    while (hasNextByte && !Scanner.isPrintableChar(buffer(ptr))) ptr += 1
    hasNextByte
  }

  def next: String = {
    if (!hasNext) throw new NoSuchElementException
    val sb = new java.lang.StringBuilder
    var b = readByte
    while (Scanner.isPrintableChar(b)) {
      sb.appendCodePoint(b)
      b = readByte
    }
    sb.toString
  }

  def nextLong: Long = {
    if (!hasNext) throw new NoSuchElementException
    var n = 0
    var minus = false
    var b = readByte
    if (b == '-') {
      minus = true
      b = readByte
    }
    if (b < '0' || '9' < b) throw new NumberFormatException

    @tailrec def loop(): Long = {
      if ('0' <= b && b <= '9') {
        n *= 10
        n += b - '0'
        b = readByte
        loop()
      } else if (b == -1 || !Scanner.isPrintableChar(b)) {
        if (minus) -n else n
      } else throw new NumberFormatException
    }

    loop()
  }

  def nextInt: Int = {
    val nl = nextLong
    if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException
    nl.toInt
  }

  def nextDouble: Double = next.toDouble
}


import scala.annotation.tailrec

object Main extends App {
  val sc = new Scanner
  val N = sc.nextInt
  val As = Seq.fill(N)(sc.nextInt).sorted

  @tailrec def loop(done: Seq[Int], queue: Seq[Int], count: Int): Int = queue match {
    case first +: second +: rest =>
      if (done.exists(first % _ == 0)) {
        loop(done, second +: rest, count)
      } else if (second == first) {
        loop(first +: done, second +: rest, count)
      } else {
        loop(first +: done, second +: rest, count + 1)
      }
    case first +: rest =>
      if (done.exists(first % _ == 0)) {
        loop(done, rest, count)
      } else {
        loop(first +: done, rest, count + 1)
      }
    case _ => count
  }

  val ans = loop(Seq.empty[Int], As, 0)
  println(ans)
}

// https://qiita.com/p_shiki37/items/a0f6aac33bf60f5f65e4
object Scanner {
  private def isPrintableChar(c: Int) = 33 <= c && c <= 126
}

class Scanner {
  private[this] val in = System.in
  private[this] val buffer = new Array[Byte](1024)
  private[this] var ptr = 0
  private[this] var buflen = 0

  private def hasNextByte: Boolean =
    if (ptr < buflen) true
    else {
      ptr = 0
      buflen = in.read(buffer)
      buflen > 0
    }

  private def readByte: Byte =
    if (hasNextByte) {
      ptr += 1
      buffer(ptr - 1)
    } else -1

  def hasNext: Boolean = {
    while (hasNextByte && !Scanner.isPrintableChar(buffer(ptr))) ptr += 1
    hasNextByte
  }

  def next: String = {
    if (!hasNext) throw new NoSuchElementException
    val sb = new java.lang.StringBuilder
    var b = readByte
    while (Scanner.isPrintableChar(b)) {
      sb.appendCodePoint(b)
      b = readByte
    }
    sb.toString
  }

  def nextLong: Long = {
    if (!hasNext) throw new NoSuchElementException
    var n = 0
    var minus = false
    var b = readByte
    if (b == '-') {
      minus = true
      b = readByte
    }
    if (b < '0' || '9' < b) throw new NumberFormatException

    @tailrec def loop(): Long = {
      if ('0' <= b && b <= '9') {
        n *= 10
        n += b - '0'
        b = readByte
        loop()
      } else if (b == -1 || !Scanner.isPrintableChar(b)) {
        if (minus) -n else n
      } else throw new NumberFormatException
    }

    loop()
  }

  def nextInt: Int = {
    val nl = nextLong
    if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException
    nl.toInt
  }

  def nextDouble: Double = next.toDouble
}


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

object Main extends App with StdInHelper {
  val n = readInt
  val as = readInts.sorted

  var res = 0

  for (i <- 0 to as.length - 1) {
    val b = new scala.util.control.Breaks
    b.breakable {
      for (j <- 0 to as.length - 1) {
        if (i != j && as(i) % as(j) == 0 && as(i) >= as(j)) {
          b.break
        }
      }
      res += 1
    }
  }
  println(res)
}

trait StdInHelper {
  def readStrings = {
    val l = readLine
    if (l == "") Array.empty[String]
    else l.split(" ")
  }
  def readInts = readStrings.map(_.toInt)
  def readLongs = readStrings.map(_.toLong)
  def readDoubles = readStrings.map(_.toDouble)
  def readBigInts = readStrings.map(BigInt.apply(_))
  def readBigDecimals = readStrings.map(BigDecimal.apply(_))
}


import java.util.Scanner

import scala.annotation.tailrec

object Main extends App {
  val sc = new Scanner(System.in)
  val N = sc.nextInt
  val As = Vector.fill(N)(sc.nextInt).sorted

  @tailrec def loop(done: Seq[Int], queue: Seq[Int], count: Int): Int = queue match {
    case first +: second +: rest =>
      if (done.exists(first % _ == 0)) {
        loop(done, second +: rest, count)
      } else if (second == first) {
        loop(first +: done, second +: rest, count)
      } else {
        loop(first +: done, second +: rest, count + 1)
      }
    case first +: rest =>
      if (done.exists(first % _ == 0)) {
        loop(done, rest, count)
      } else {
        loop(first +: done, rest, count + 1)
      }
    case _ => count
  }

  val ans = loop(Seq.empty[Int], As, 0)
  println(ans)
}


import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)
  val N = sc.nextInt
  val A = Array.fill(N)(sc.nextInt).sorted

  var x = Array.fill(N)(false)
  if (A(0) == A(1)) x(0) = true
  for (i <- 1 until N) {
    @scala.annotation.tailrec
    def loop(j: Int = 0): Unit = {
      if (A(i) % A(j) == 0) x(i) = true
      if (j + 1 < i) loop(j + 1)
    }

    loop()
  }
  println(x.count(!_))
}


import java.io.{BufferedOutputStream, BufferedReader, InputStreamReader, PrintWriter}
import java.lang

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import scala.reflect.ClassTag

object Main {
  def get[T: ClassTag](implicit in: BufferedReader, converter: String => T): T = {
    converter(in.readLine)
  }

  def getArray[T: ClassTag](implicit in: BufferedReader, converter: String => T): Array[T] = {
    get[String].split("\\s+").map[T](converter)
  }

  implicit val idConverter: String => String = s => s
  implicit val intConverter: String => Int = s => Integer.parseInt(s)
  implicit val longConverter: String => Long = s => lang.Long.parseLong(s)

  def get[T1, T2](
                   implicit in: BufferedReader,
                   converter1: String => T1,
                   converter2: String => T2
                 ): (T1, T2) = {
    getArray[String] match {
      case Array(v1, v2) => (converter1(v1), converter2(v2))
    }
  }

  def get[T1, T2, T3](
                       implicit in: BufferedReader,
                       converter1: String => T1,
                       converter2: String => T2,
                       converter3: String => T3
                     ): (T1, T2, T3) = {
    getArray[String] match {
      case Array(v1, v2, v3) => (converter1(v1), converter2(v2), converter3(v3))
    }
  }

  implicit class TimesInt(val n: Int) {
    def times(f: Int => Unit): Unit = {
      for (i <- 0 until n) {
        f(i)
      }
    }
  }

  def primes(n: Long): ArrayBuffer[Long] = {
    val buf = ArrayBuffer.empty[Long]
    val s = Math.sqrt(n).toInt

    var v = n
    for (i <- 2 to s) {
      if (v == 1 || v == 0) {
        return buf
      } else {
        while (v % i == 0) {
          buf.append(i)
          v /= i
        }
      }
    }
    if (v > s) {
      buf.append(v)
    }
    buf
  }

  def divisors(n: Int): ArrayBuffer[Int] = {
    val buf = ArrayBuffer.empty[Int]
    val s = Math.sqrt(n).toInt

    for (i <- 1 to s) {
      if (n % i == 0) {
        buf.append(i)
        if (i != n / i) {
          buf.append(n / i)
        }
      }
    }
    buf
  }

  def main(args: Array[String]): Unit = {
    implicit val in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    val out = new PrintWriter(new BufferedOutputStream(System.out))
    val n = get[Int]
    val as = getArray[Int]

    val map = Array.ofDim[Int](1000001)
    for (a <- as) {
      map(a) += 1
    }

    var count = 0
    for (a <- as) {
      if (divisors(a).forall(d =>
        if (a == d) {
          map(d) == 1
        } else {
          map(d) == 0
        }
      )) {
        count += 1
      }
    }

    out.println(count)
    out.flush()
  }

}


import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)
  val N = sc.nextInt
  val A = Array.fill(N)(sc.nextInt)

  val x = Array.fill(N)(true)
  for (i <- 0 until N) {
    for (j <- i + 1 until N) {
      if (A(i) % A(j) == 0) {
        x(i) = false
      }
    }
  }
  val z = x.count(x => x) - 1
  println(z)
}


object Main extends App {
  @scala.annotation.tailrec
  def loop(acc: BigInt, list: List[BigInt]): BigInt =
    list match {
      case _ if 1000000000000000000L < acc => -1
      case Seq() => acc
      case x :: xs => loop(acc * x, xs)
    }

  val sc = new java.util.Scanner(System.in)
  val list@x :: xs = List.fill(sc.nextInt())(BigInt(sc.nextBigInteger()))
  println(if (list.contains(0)) 0 else loop(x, xs))
}

Score : 200 points

Problem Statement

Given N integers A_1, ..., A_N, compute A_1 \times ... \times A_N.

However, if the result exceeds 10^{18}, print -1 instead.

Constraints

2 \leq N \leq 10^5

0 \leq A_i \leq 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 ... A_N

Output

Print the value A_1 \times ... \times A_N as an integer, or -1 if the value exceeds 10^{18}.

Sample Input 1

2
1000000000 1000000000

Sample Output 1

1000000000000000000

We have 1000000000 \times 1000000000 = 1000000000000000000.

Sample Input 2

3
101 9901 999999000001

Sample Output 2

-1

We have 101 \times 9901 \times 999999000001 = 1000000000000000001, which exceeds 10^{18}, so we should print -1 instead.

Sample Input 3

31
4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4 6 2 6 4 3 3 8 3 2 7 9 5 0

Sample Output 3

0


object Main extends App {
  @scala.annotation.tailrec
  def loop(acc: Long, longs: List[Long]): Long =
    if (acc == 0) {
      0
    } else if (acc < 0 || 1000000000000000000L < acc) {
      -1L
    } else {
      longs match {
        case Seq() => acc
        case x :: xs => loop(acc * x, xs)
      }
    }

  val sc = new java.util.Scanner(System.in)
  val x :: xs = List.fill(sc.nextInt())(sc.nextLong())
  println(loop(x, xs))
}


import java.util.Scanner

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

  val n = scala.io.StdIn.readInt()
  val A = scala.io.StdIn.readLine().split(" ").map(BigInt(_))

  def solve(): BigInt = {
    val limit = BigInt(1000000000000000000L)

    if(A.contains(0)) return 0
    A.foldLeft(BigInt(1)) { (acc, num) =>
      if(acc * num > limit) return BigInt(-1)
      else acc * num
    }
  }

  println(solve())

}


import java.util.Scanner

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

  val n = scala.io.StdIn.readInt()
  val A = scala.io.StdIn.readLine().split(" ").map(BigInt(_))

  def solve(): BigInt = {
    val limit = BigInt(1000000000000000000L)
    val product = A.product
    if(product > limit) BigInt(-1) else product
  }

  println(solve())

}


import java.util.Scanner

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

  val n = scala.io.StdIn.readInt()
  val A = scala.io.StdIn.readLine().split(" ").map(_.toLong)

  def solve(): Long = {
    val product = A.product
    if(product > 1000000000000000000L) -1L else product
  }

  println(solve())

}


object Main extends App{
  val sc = new java.util.Scanner(System.in)
  var n = sc.nextInt()
  val a = Array.fill(n)(sc.nextLong())
  var num = BigInt("1")
  if (a.indexOf(0) != -1) {print(0);sys.exit()}
  for (i <- 0 until n){
    num *= a(i)
    if (num >= 1000000000000000000L){ print(-1);sys.exit();}
  }
  println(num)
}


import scala.annotation.tailrec
import scala.io.StdIn.{readInt, readLine}

object Main extends App {
  import Implicits.ListOps

  val Zero = BigInt(0)
  val VMax = BigInt(1_000_000_000_000_000_000L)

  val n  = readInt()
  val xs = readLine().split(' ').view.map { BigInt(_) }.toList

  val (s, isOver) =
    if (xs.contains(Zero)) (Zero, false)
    else {
      val (s, ys) = xs.reduceWhile { _ * _ } { _ <= VMax }
      (s, ys.nonEmpty)
    }

  println(if (isOver) -1 else s)
}

/**
  * 拡張メソッド群
  */
object Implicits {

  /**
    * List用拡張メソッド
    * @param self 自身を表すList
    * @tparam A 要素の型
    */
  implicit class ListOps[A](self: List[A]) {

    /**
      * 条件を満たし続ける限りListの要素を集約する
      * 条件を満たさなくなった時点で処理を打切る
      * @param z 初期値
      * @param op 集約演算用の関数
      * @param p 処理を続けるかどうかを判定する述語関数
      * @return 条件を満たさなくなった時点のそれまでの計算結果と残りのリストListの組
      */
    def foldWhile[B](z: B)(op: (B, A) => B)(p: B => Boolean): (B, List[A]) = {

      @tailrec
      def loop(accum: B, zs: List[A]): (B, List[A]) = zs match {
        case Nil => (accum, Nil)
        case x :: xs =>
          val s = op(accum, x)
          if (p(s)) loop(s, xs) else (accum, zs)
      }

      loop(z, self)
    }

    /**
      * foldWhileの初期値を自身の先頭要素にした関数
      */
    def reduceWhile(op: (A, A) => A)(p: A => Boolean): (A, List[A]) = self match {
      case Nil     => throw new UnsupportedOperationException("empty list")
      case x :: xs => xs.foldWhile(x)(op)(p)
    }
  }
}


import scala.annotation.tailrec
import scala.io.StdIn.{readInt, readLine}

object Main extends App {
  import Implicits.ListOps

  val Zero = BigInt(0)
  val VMax = BigInt(1_000_000_000_000_000_000L)

  val n  = readInt()
  val xs = readLine().split(' ').view.map { BigInt(_) }.toList

  val (s, isOver) =
    if (xs.contains(Zero)) (Zero, false)
    else {
      val (s, ys) = xs.reduceWhile { _ * _ } { _ <= VMax }
      (s, ys.nonEmpty)
    }

  println(if (isOver) -1 else s)
}

/**
  * 拡張メソッド群
  */
object Implicits {

  /**
    * List用拡張メソッド
    * @param self 自身を表すList
    * @tparam A 要素の型
    */
  implicit class ListOps[A](self: List[A]) {

    /**
      * 条件を満たし続ける限りListの要素を集約する
      * 条件を満たさなくなった時点で処理を打切る
      * @param z 初期値
      * @param op 集約演算用の関数
      * @param p 処理を続けるかどうかを判定する述語関数
      * @return 条件を満たさなくなった時点のそれまでの計算結果と残りのリストListの組
      */
    def foldWhile[B](z: B)(op: (B, A) => B)(p: B => Boolean): (B, List[A]) = {

      @tailrec
      def go(zs: List[A], accum: B): (B, List[A]) = zs match {
        case Nil => (accum, Nil)
        case x :: xs =>
          val s = op(accum, x)
          if (p(s)) go(xs, s) else (accum, zs)
      }

      go(self, z)
    }

    /**
      * foldWhileの初期値を自身の先頭要素にした関数
      */
    def reduceWhile(op: (A, A) => A)(p: A => Boolean): (A, List[A]) =
      self.tail.foldWhile(self.head)(op)(p)
  }
}


import scala.io.StdIn.{readInt, readLine}

object Main extends App {
  val Zero = BigInt(0)
  val VMax = BigInt(1_000_000_000_000_000_000L)

  val n  = readInt()
  val xs = readLine().split(' ').map { BigInt(_) }

  var isOver = false
  val s =
    if (xs.contains(Zero)) Zero
    else {
      val it = xs.iterator
      var s  = BigInt(1)
      while (it.hasNext && !isOver) {
        val a = it.next()
        s *= a
        if (s > VMax) {
          isOver = true
        }
      }
      s
    }

  println(if (isOver) -1 else s)
}


import java.util.Scanner

object Main extends App {
  val VMax = BigInt(1_000_000_000_000_000_000L)

  val sc     = new Scanner(System.in)
  val n      = sc.nextInt()
  var isOver = false
  var s      = BigInt(1)
  var i      = 0
  while (i < n && !isOver && s != 0) {
    val a = BigInt(sc.next())
    val x = s * a
    if (x <= VMax) {
      s = x
    } else {
      isOver = true
    }
    i += 1
  }

  println(if (isOver) -1 else s)
}


import scala.io.StdIn._

object Main extends App {
  readInt()
  val xs = readLine().split(' ').map { BigInt(_) }

  val s = xs.product
  println(if (s <= 1_000_000_000_000_000_000L) s else -1)

}


object Main extends App {
  import io.StdIn.readLine
  val xs = readLine().split("_").map(_.toLong)
  val M   = 1e+18.toLong
  val Array(x, rest @ _*) = xs
  val n = rest.foldLeft(x)((a, b) => a * b)
  // println(xs.mkString(",") + " ==>")
  println(if (-1 < n && n <= M) n else -1)
}


object Main extends App {

  def run(): Unit = {
    import io.StdIn._
    val _   = readLine().toInt
    val xs  = readLine().split("\\s").map(_.toLong)
    val M   = 1e+18.toLong

    xs.find(_ == 0) match {
      case Some(_) =>
        println(0)

      case _ =>
        val Array(x, rest @ _*) = xs
        val n = rest.foldLeft(x)((a, b) => a * b)

        println(if (M < n) -1 else n)
    }
  }

  run()
}


object Main extends App {

  def run(): Unit = {
    import io.StdIn._
    val _ = readLine().toInt
    val Array(x, xs @ _*) = readLine().split("\\s").map(_.toLong)

    val M = 1e+18.toLong
    var n = x
    var exit = false
    val it = xs.iterator
    while (!exit && it.hasNext) {
      if (n < 0 || M < n) {
        exit = true
      }
      n = n * it.next
    }
    println(if (exit || M < n) -1 else n)
  }

  run()
}


object Main extends App {

  def run(): Unit = {
    import io.StdIn._
    val _ = readLine().toInt
    val Array(a, rest @ _*) = readLine().split("\\s").map(_.toLong)
    val it = rest.iterator

    val M = 1e+18.toLong
    var n = a
    while (it.hasNext) {
      if (M < n) {
        println(-1)
        return ()
      }
      n = n * it.next
    }
    println(n)
  }

  run()
}


import java.util.Scanner
import scala.annotation.tailrec

object Main extends App {
  val sc = new Scanner(System.in)
  val n = sc.nextInt
  val a = Seq.fill(n)(BigInt(sc.nextLong))
  val maxNum = BigInt("1000000000000000000")

  if (a.contains(BigInt(0))) {
    println(0)
  } else {
    println(loop(BigInt(1), a))
  }

  @tailrec def loop(acc: BigInt, li: Seq[BigInt]): BigInt = li match {
    case _ if (acc > maxNum) => BigInt(-1)
    case x::xs => loop(acc * x, xs)
    case _ => acc
  }
}


import java.math.BigInteger
import java.util.Scanner

import scala.annotation.tailrec

object Main extends App {
  val sc = new Scanner(System.in)
  val N = sc.nextInt

  val limit = BigInt("1000000000000000000")

  @tailrec def lp(acc: BigInt, cnt: Int): BigInt = {
    if (acc > limit) {
      BigInt(-1)
    } else if (cnt == 0) {
      acc
    } else {
      lp(acc * BigInt(sc.nextBigInteger), cnt - 1)
    }
  }

  println(lp(BigInt(BigInteger.ONE), N))
}


import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)
  val N = sc.nextInt
  val result = Seq.fill(N)(BigInt(sc.nextLong)).product
  println(if (result > BigInt("1000000000000000000")) "-1" else result)
}


import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)
  val N = sc.nextInt
  val result = Seq.fill(N)(BigInt(sc.next)).product
  println(if (result > BigInt("1000000000000000000")) "-1" else result)
}