Evaluating e^x – HackerRank Solution

In this post, we will solve Evaluating e^x HackerRank Solution. This problem (Evaluating e^x) is a part of HackerRank Functional Programming language.

Task

The series expansion of ex is given by:

1 + x + x2/2! + x3/3! + x4/4! + . . . . . .

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

Input Format

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

Output Format

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

Constraints

  • 1 <= N <= 50
  • -20.00 <= x <= 20.00
  • 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

Explanation

The output has the computed values of ex corresponding to each test case. They are correct up to 4 decimal places and on separate lines.

Scoring

All test cases carry an equal weight in the final score. For your solution to pass a given test case, all the values of ex computed by you must be within +/-0.1 of the expected answers. This tolerance level has been kept to account for slightly different answers across different languages.

Solution – Evaluating e^x – HackerRank Solution

Haskell

import Control.Applicative
import Control.Monad
import System.IO

eee :: Double -> Double -> Double
eee 1 x = x + 1
eee n x = ((x**n) / (product [1..n])) + (eee (n-1) x)

main :: IO ()
main = do
    n_temp <- getLine
    let n = read n_temp :: Int
    forM_ [1..n] $ \a0  -> do
        x_temp <- getLine
        let x = read x_temp :: Double
        print (eee 9 x)


getMultipleLines :: Int -> IO [String]

getMultipleLines n
    | n <= 0 = return []
    | otherwise = do
        x <- getLine
        xs <- getMultipleLines (n-1)
        let ret = (x:xs)
        return ret

Note: This problem (Evaluating e^x) is generated by HackerRank but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.

Leave a Comment

Your email address will not be published. Required fields are marked *