algorithme factorielle

This commit is contained in:
gwen 2017-04-06 16:57:22 +02:00 committed by Benjamin Bohard
parent 55234742c5
commit 859f2cdf1c
3 changed files with 78 additions and 0 deletions

View File

@ -110,6 +110,55 @@ Exemple d'algorithme
\end{algorithmic}
\end{algorithm}
Exemple d'algorithme avec deux implémentations
-----------------------------------------------
Soit l'algorithme de factorielle suivant :
.. raw:: latex
\begin{algorithm}
\caption{Algorithme de la factorielle d'un nombre}\label{factorielle}
\begin{algorithmic}[1]
\Function{factorielle}{$n$}\Comment{La fonction récursive factorielle}
\BState \emph{parametre} : $n$ entier
\If{$n = 1$}
\BState \emph{Return} : 1
\Else
\BState \emph{Return} : $n * \Call{factorielle}{n-1}$
\EndIf
\EndFunction
\end{algorithmic}
\end{algorithm}
Ou encore, en **pseudocode** (algorithme vague) :
.. function:: factorielle(n:int)
::
begin
if n=1
return 1
else
return n * factoriel(n-1)
end if
end
Implémentation en python :
.. literalinclude:: code/factorielle.py
:language: python
Implémentation en OCaml :
.. literalinclude:: code/factorielle.ml
:language: ocaml
Qualité d'un algorithme
-----------------------

View File

@ -0,0 +1,17 @@
let rec fact = function
|1 -> 1
| n -> n * fact (n-1) ;;
let print_fact n =
Printf.printf "factorielle %i = %i\n" n (fact n)
let main () =
begin
print_fact 5 ;
print_newline () ;
exit 0 ;
end
let _ = main ()

View File

@ -0,0 +1,12 @@
def factorielle(n):
if (n > 1):
r = n*factorielle(n-1)
else:
r = 1
return r
def print_fact(n):
print "factorielle {} = {}\n".format(5, factorielle(5))
if __name__ == '__main__':
print_fact(5)