2021년 4월 14일 수요일

[ Practice Scala ] 재귀함수 (Evaluating e^x)


문제 ]

The series expansion of  is given by:

 

Evaluate  for given values of  by using the above expansion for the first  terms.

Input Format

The first line contains an integer , the number of test cases.
 lines follow. Each line contains a value of  for which you need to output the value of  using the above series expansion. These input values have exactly  decimal places each.

Output Format

Output  lines, each containing the value of , computed by your program.

Constraints



VarVal in Scala and def and defn in Clojure are blocked keywords. The challenge is to accomplish this without either mutable state or direct declaration of local variables.

Sample Input

4
20.0000
5.0000
0.5000
-0.5000

Sample Output

2423600.1887
143.6895
1.6487
0.6065


제출 ]

import java.io._
import java.math._
import java.security._
import java.text._
import java.util._
import java.util.concurrent._
import java.util.function._
import java.util.regex._
import java.util.stream._

object Solution {

    def f(x: Double): Double ={
      f2(x, 9)
    }
 
    def fact(x: Int): Int = if (x <= 11 else x * fact(x - 1)
 
    def f2(x: Double, i: Int): Double = {
      if (i == 01 else Math.pow(x, i) / fact(i) + f2(x, i - 1)
    }

    def main(args: Array[String]) {
        val stdin = scala.io.StdIn

        val n = stdin.readLine.trim.toInt

        for (nItr <- 1 to n) {
            val x = stdin.readLine.trim.toDouble
            println(f(x))
        }
    }
}


풀이 ]
x제곱/i!에 대한 재귀, i팩토리얼에 대한 재귀함수



댓글 없음:

댓글 쓰기