fact

fact.c

/*

Profil
###### 

fact: entier_nat -> entier_nat

Exemples
###### 

fact(0) = 1
fact(1) = 1
fact(2) = 2
fact(3) = 6
fact(4) = 24 = 4*fact(3) 
             = 4*3*fact(2)
             = 4*3*2*fact(1)
             = 4*3*2*1*fact(0)
             = 4*3*2*1*1

Axiomes
###### 

fact(zero()) = 1
fact(succ(n)) = succ(n)*fact(n)

Algorithme recursif
###### 

fonction fact(n: entier_nat): entier_nat
debut
 | si est_nul(n)
 | -------------
 |               | alors retourner 1              
 |               | sinon retourner n*fact(prec(n))
 | finsi        
fin

Algorithme iteratif
###### 

fonction fact(n: entier_nat): entier_nat
debut
 | resultat: entier_nat        
 | --------------------        
 | resultat := 1               
 | tantque non est_nul(n) faire
 |                              | resultat := resultat * n
 |                              | n := prec(n)            
 | fintantque                  
 | retourner resultat          
fin

*/

#include `<stdio.h>`

#include `<stdbool.h>`
#include "entier_nat.h"

int fact_recursif(int n)
{
    if (est_nul(n))
    { 
    return 1;
    }
    else
    {
    return n*fact_recursif(prec(n));
    }
}

int fact_iteratif(int n)
{
    int res = 1;
    while ( n != 0 )
    {
    res = n*res;
    n = n-1;
    }
    return res;
}

void test_recursif(int n)
{
    printf("La factorielle (recursive) de %d vaut %d\n", n, fact_recursif(n));
}

void test_iteratif(int n)
{
    printf("La factorielle (iterative) de %d vaut %d\n", n, fact_iteratif(n));
}

int main()
{
    int i;
    for (i = 0; i <= 6; i = i+1)
    {
    test_recursif(i);
    test_iteratif(i);
    }
}