Dados x e um vetor com n+1 números a0,a1,a2,…,an, onde n≥0, calcular: a0x(0)+a1x(1)+a2x(2)+…+anx(n), sendo x(k)=x(x−1)(x−2)…(x−k+1) o polinômio fatorial de grau k. Considere que x(0)=1.
Procure utilizar o menor número possível de multiplicações e adições em seu algoritmo.
Solução:
Com recursão:
\begin{algorithm} \begin{algorithmic} \FUNCTION{PoliFat}{$x, a$} \STATE $n \gets \textrm{size}(a) - 1$ \IF{$n = 0$} \RETURN $a[0]$ \ELSE \RETURN $a[0] + x$ * \textsc{PoliFat}$(x-1, a[1..n])$ \ENDIF \ENDFUNCTION \end{algorithmic} \end{algorithm}
1:function PoliFat(x,a)
2:n←size(a)−1
3:if n=0 then
4:return a[0]
5:else
6:return a[0]+x * PoliFat(x−1,a[1..n])
7:end if
8:end function
Com iteração:
\begin{algorithm} \begin{algorithmic} \FUNCTION{PoliFat}{$x, a$} \STATE $n \gets \textrm{size}(a) - 1$ \STATE $sum \gets a[n]$ \FOR{$k \gets n-1$ \textbf{downto} 0} \STATE $sum \gets sum * (x - k) + a[k]$ \ENDFOR \RETURN $sum$ \ENDFUNCTION \end{algorithmic} \end{algorithm}
1:function PoliFat(x,a)
2:n←size(a)−1
3:sum←a[n]
4:for k←n−1 downto 0 do
5:sum←sum∗(x−k)+a[k]
6:end for
7:return sum
8:end function