diff --git a/slides/cours_7.md b/slides/cours_7.md index 30ba9166155ec2f2b591923f227d839e49a1a693..6f49c3a66052f82d0bc268b219dfc6fbbdc86eb4 100644 --- a/slides/cours_7.md +++ b/slides/cours_7.md @@ -14,12 +14,13 @@ header-includes: | . . . ```C -int pow(int x, int n) { +double pow(double x, int n) { if (0 == n) { return 1; } + double p = c; for (int i = 1; i < n; ++i) { - x = x * x; // x *= x + p = p * x; // x *= x } return x; } @@ -38,7 +39,7 @@ int pow(int x, int n) { . . . ```C -int pow(x, n) { +double pow(double x, int n) { if (n != 0) { return x * pow(x, n-1); } else { @@ -71,8 +72,8 @@ $$ ## Le vrai algorithme -* Si n est pair: calculer $\left(x^{n/2}\right)^2$, -* Si n est impair: calculer $x \cdot \left(x^{(n-1)/2}\right)^2$. +* Si n est pair: calculer $\left(x^{n/2}\cdot x^{n/2}\right)$, +* Si n est impair: calculer $x \cdot \left(x^{(n-1)/2}\right)^2=x\cdot x^{n-1}$. ## Exercice: écrire l'algorithme récursif correspondant @@ -80,8 +81,8 @@ $$ ```C double pow(double x, int n) { - if (1 == n) { - return x; + if (0 == n) { + return 1; } else if (n % 2 == 0) { return pow(x, n / 2) * pow(x, n/2); } else {