// td2.c

#include <stdio.h>
#include <assert.h>
#include <stdlib.h>

int main() {
	// TD 1
	// factorielle
	system("cls");
{
	const unsigned int n=5;	// il faut calculer n!
	unsigned int i=0;		// i varie de 0 à n
	unsigned int f=1;		// f == i! 

	while (i !=n) { 
		++i;					
		f *= i;				// pour qu'on ait toujours f == i!
	}
	// ici on sait que f==i! et que i==n donc f==n!
	printf("%u! = %u\n", n, f);
}
{	const unsigned int n=5;
	unsigned int i;
	unsigned int f;

	for (i=0, f=1; i!=n; ++i)
		f *= i+1;			// car i n'a pas encore été incrémenté
	printf("%u! = %u\n", n, f);
}
	system("pause");
	system("cls");
	// TD 2
	// diviseurs d'un nombre
{	
	const unsigned int n= 60;
	unsigned int d;
	unsigned int par_ligne = 3;
	unsigned int NbDiviseurs =0;

	printf("Les diviseurs de %i sont : ", n);
	for (d=1; d <= n; ++d)
		if (n %d == 0)
			printf("%u ", d);
	printf("\n");
	system("pause");

	printf("Les diviseurs de %u (%u par ligne) sont :\n", n, par_ligne);
	for (d=1; d <= n; ++d)
		if (n %d ==0)
		{ printf("%u ", d);
		  ++NbDiviseurs;
		  if (NbDiviseurs % par_ligne == 0)
				printf("\n");
		}
	printf("\n");
}
	system("pause");
	system("cls");

	// TD 3
	// pgcd
{	const unsigned int a0=60, b0=42; // valeurs initiales de a et b
	unsigned int a=a0;
	unsigned int b=b0;
	unsigned int r=0;
	// pgcd(a,b) = pgcd(a0,b0) doit rester vrai

	while(b != 0) {	// atteint car d diminue à chaque étape
		r = a%b;
		a = b;
		b = r;		// pgcd(a,b) reste égal à pgcd(a0,b0) car pgcd(a,b) = pgcd(b, a%b)
	}
	printf("Le pgcd de %u et %u est %u\n", a0,b0,a);
}
	system("pause");
	system("cls");

	// TD 4
	// test de primalité
 { const unsigned int n= 10;
 	 unsigned int d;
	assert(n >= 2);

	for (d=2; d*d <= n && n%d !=0; ++d)
		;
	if (n%d == 0 && d != n)
		printf("%u n'est PAS premier\n", n);
	else 
		printf("%u est premier\n", n);
}
 	system("pause");
	system("cls");

	// TD 5
	// crible d'Eratosthène
{	enum {MAX = 100};
	unsigned int i, j, 	crible[MAX+1];
	unsigned int	nbPaA = 30,			// nombre de nombre premiers à afficher (au maximum)
								nbPremiers =0;  // nombre premiers trouvés
	// 2 <= k <= MAX est premier si crible[k] == 1
	// et si k a été vérifié c'est à dire si tous ses diviseurs potentiels ont été testés
	// c'est à dire si i >= k
 
	for(j=2; j <= MAX; ++j){
		crible[j]=1;
	}

	for(i=2; i<=MAX && nbPremiers < nbPaA; ++i){
		if (crible[i] == 1) {
			++nbPremiers;
			printf("%u ", i);
			for (j =i; i*j <= MAX; ++j)
				crible[i*j] = 0;
		}
	}
	printf("\n");
}
	system("pause");
	return 0;
}