Error in calculating a PA with Haskell

Asked

Viewed 72 times

3

The function does not return the expected result but I followed the formula and can not understand the error in logic. I hope to return the term i-th.

termoPA :: Int -> Int -> Int -> Int 

termoPA p1 r i | i == 0 = 0
               | otherwise = p1 + r * termoPA p1 r (i-1)

1 answer

1


The formula of General Term of PA or nth term is given by:

inserir a descrição da imagem aqui

where:

  • a1 is the first term of PA.

  • r is the reason for PA.

  • n is the n-th term index of PA..

Using the color formula:

termoPA :: Int -> Int -> Int -> Int 
termoPA a1 r n | n == 0 = 0
               | otherwise = a1 + (n -1) * r

Example:

Given a PA (1, 4, 7, 10, 13, 16, 19, …) where the first term is 1 the reason is 3 the 7th term will be:

main = print(termoPA 1 3 7)
> 19

Test the example in Repl.it: https://repl.it/repls/AnnualSparklingTranslations

The recursive algorithm, which I consider counterproductive because the previous algorithm offers the same result in a single passage and this need of n-passages to obtain it, constitutes incrementing p1 in r as we descend n, returning p1 when n == 1:

termoPA :: Int -> Int -> Int -> Int 

termoPA p1 r n | n == 0 = 0
               | n == 1 = p1
               | otherwise = termoPA (p1 + r) r (n-1)

Using the same AP from the previous example:

main = print(termoPA 1 3 6)
>16

Test here on Repl.it: https://repl.it/repls/RotatingGenerousRedundantcode

  • PS: If you have doubts about my assertion that the second algorithm is counterproductive test on both algorithms termoPA 1 3 99999999999999999.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.