[Précédent]
[Index] | [Enoncé] | [Version imprimable]
[Prochain]

3.8
  Plus Grand Diviseur Commun - Corrigé
Niveau 2
 
 
Fichiers:
  PGDC.java    

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.util.Scanner;

class PGDC {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
         
        System.out.println("Calcul du plus grand  diviseur commun de deux nombres entiers positifs.");
        // Entrée des données
        System.out.print("Entrez un nombre positif :  ");
        int nb1 = scanner.nextInt();
        System.out.print("Entrez un nombre positif :  ");
        int nb2 = scanner.nextInt();

        /* 
         * A chaque passage de la boucle while, on modifie le plus grand
         * de a et b en déduisant le nombre plus petit, comme indiqué par
         * la formule d'Euclide. La boucle se terminera quand a et b sont
         * égaux (au pire des cas quand ils valent 1). A ce moment-là, on
         * retourne la valeur de a (on aurait aussi pu retourner b). 
         */
        int a = nb1;
        int b = nb2;

        while (a != b) {
            if (a > b) {
                a = a - b;
            } else {
                b = b - a;
            }
        }

        System.out.println("Le plus grand diviseur commun de " + nb1 + " et " + nb2 + " est " + a);

        scanner.close();
    }
}

Il existe une solution dite récursive du calcul du PGDC un peu plus intuitive à écrire.

Nous verrons la récursion en fin de semestre.

 


[Précédent]
[Index] | [Enoncé] | [Version imprimable]
[Prochain]