import scala.annotation.tailrec import scala.collection.immutable.IndexedSeq import scala.io.StdIn object Problem294 { def ncr(n: BigInt, r: BigInt): Int = { val numer = (n to n - r + 1 by -1).product val denom = (r to 1 by -1).product (numer / denom).toInt } def makeResult(resultBits: BigInt, ansLen: Int): String = { val temp = (resultBits.bitLength - 1 to 0 by -1).foldLeft("") { (sum, x) => val b = if (resultBits.testBit(x)) "5" else "3" sum + b } "3" * (ansLen - resultBits.bitLength) + temp } @tailrec def findNth[A](n: Int, list: Seq[A], f: A => Boolean): A = { if (f(list.head)) { if (n == 1) { list.head } else { findNth(n - 1, list.tail, f) } } else { findNth(n, list.tail, f) } } def proc(N: Int): String = { val counts: IndexedSeq[Int] = (1 to 25).scanLeft(0) { (totalCount, len) => val numOf5: Int = len - len % 3 val count = (3 to numOf5 by 3).fold(0)((sum, x) => sum + ncr(len - 1, len - x) ) totalCount + count } val (small, large) = counts.zipWithIndex.span(x => x._1 < N) val start = small.last._1 val ansLen = large.head._2 val searchRange = 0 until Math.pow(2, ansLen - 1).toInt val f: Int => Boolean = Integer.bitCount(_) % 3 == 2 val resultBits = (findNth(N - start, searchRange, f) << 1) + 1 makeResult(resultBits, ansLen) } def main(args: Array[String]) { val N = StdIn.readInt() val result: String = proc(N) println(result) } }