Scala: the best solution

  We define the supervalue of an integer x using the following rules:

Iff x has only 1 digit, then its super digit is x.
Otherwise, the super digit of x is equal to the super digit of the digit-sum of x. Here, digit-sum of a number is defined as the sum of its digits.
For example, super digit of 9875 will be calculated as:

super-digit(9875) = super-digit(9+8+7+5) 
                  = super-digit(29) 
                  = super-digit(2+9)
                  = super-digit(11)
                  = super-digit(1+1)
                  = super-digit(2)
                  = 2.
You are given two numbers - n k. You have to calculate the super digit of P.

P is created when number n is concatenated k times. That is, if n = 123 and k = 3, then P = 123123123.

Input Format 
Input will contain two space separated integers, n and k.

Output Format

Output the super digit of P, where P is created as described above.


Sample Input

148 3
Sample Output

Here n = 148 and k = 3, so P = 148148148.

super-digit(P) = super-digit(148148148) 
               = super-digit(1+4+8+1+4+8+1+4+8)
               = super-digit(39)
               = super-digit(3+9)
               = super-digit(12)
               = super-digit(1+2)
               = super-digit(3)
               = 3.


I wrote the following program to solve the above problem, but how to solve it even efficiently and works with a string than a math operation? and for multiple inputs it takes a long time like

861568688536788 100000

object SuperDigit {
  def main(args: Array[String]) {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution
    def generateString (no:String,re:BigInt , tot:BigInt , temp:String):String = {
      if(tot-1>re) generateString(no+temp,re+1,tot,temp)
      else no
    def totalSum(no:List[Char]):BigInt = no match {
      case x::xs =>  x.asDigit+totalSum(xs)
      case Nil => '0'.asDigit


    def tot(no:List[Char]):BigInt = no match {
      case _ if no.length == 1=> no.head.asDigit
      case no => tot(totalSum(no).toString.toList)

    var list = readLine.split(" ");
    var one = list.head.toString();
    var two = BigInt(list(1));




source to share

1 answer

One solution is to understand that you do not need to concatenate a number considered as a string k times, but can start with k * qs (n) (where qs is a function that maps a number to its sum of digits, i.e. i.e. qs (123) = 1 + 2 + 3). Here's a more functional programming style. I don't know if it can be done faster than this.

object Solution {

  def qs(n: BigInt): BigInt = n.toString.foldLeft(BigInt(0))((n, ch) => n + (ch - '0').toInt)

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

    val Array(n, k) =" ").map(BigInt(_))

    println(Stream.iterate(k * qs(n))(qs(_)).find(_ < 10).get)




All Articles