|
| 1 | +import scala.collection.mutable.ArrayBuffer |
| 2 | + |
| 3 | +object Solution { |
| 4 | + |
| 5 | + val in = { |
| 6 | + val lines = scala.io.Source.stdin.getLines |
| 7 | + lines flatMap (_ split ' ' filter (_.nonEmpty)) |
| 8 | + } |
| 9 | + |
| 10 | + def nextInt = in.next.toInt |
| 11 | + def nextLong = in.next.toLong |
| 12 | + |
| 13 | + val primes: Stream[Int] = 2 #:: (Stream.from(3, 2) filter (n => primes.view takeWhile (p => p*p <= n) forall (n % _ != 0))) |
| 14 | + val primes106 = primes takeWhile (_ < 1000100) toArray |
| 15 | + |
| 16 | + @annotation.tailrec |
| 17 | + def largestPrimeFactor(n: Long, index: Int): Long = { |
| 18 | + val p: Long = primes106(index) |
| 19 | + if (p*p > n) n |
| 20 | + else |
| 21 | + if (n % p == 0) { |
| 22 | + if (n == p) p |
| 23 | + else largestPrimeFactor(n/p, index) |
| 24 | + } else |
| 25 | + largestPrimeFactor(n, index + 1) |
| 26 | + } |
| 27 | + |
| 28 | + def main(args: Array[String]): Unit = { |
| 29 | + val testCount = nextInt |
| 30 | + for (test <- 1 to testCount) { |
| 31 | + val N = nextLong |
| 32 | + println(largestPrimeFactor(N, 0)) |
| 33 | + } |
| 34 | + } |
| 35 | +} |
0 commit comments