The formula of General Term of PA or nth term is given by:
where:
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
.– Augusto Vasques