Exercices-Java le moins commun multiple (deux méthodes)

Multiple moins commun

1. Trouvez d'abord le plus grand diviseur commun, puis a * b / le plus grand diviseur commun

import java.util.Scanner;
public class TestDemo1 {
    
    
    public static void main(String[] args) {
    
    
        Scanner scan = new Scanner(System.in);
        int a = scan.nextInt();
        int b = scan.nextInt();
        int tmp = a*b / gcd(a,b);
        System.out.println(tmp);
    }
    public static int gcd(int a, int b){
    
    
        while(b != 0){
    
    
            int tmp = a % b;
            a = b;
            b = tmp;
        }
        return a;
    }
}

2. Méthode de réflexion du programme

  • Informations cachées: le plus petit commun multiple doit être supérieur ou égal à la valeur maximale entre les deux nombres
import java.util.Scanner;
public class TestDemo1 {
    
    
    public static void main(String[] args) {
    
    
        Scanner scan = new Scanner(System.in);
        int a = scan.nextInt();
        int b = scan.nextInt();

        int max = a > b ? a : b;
        while(max > 0){
    
    
            if(max % a == 0 && max % b == 0){
    
    
                break;
            }
            max++;
        }
        System.out.println(max);
    }
}

Je suppose que tu aimes

Origine blog.csdn.net/qq_45665172/article/details/111190567
conseillé
Classement