求最大公约数

第一种方法

import java.util.*;
class Main {
  public static void main(String[] args){
    //Create a scanner
    Scanner input = new Scanner(System.in);
    //Prompt the user to enter two integers
    System.out.print("Enter first integer: ");
    int n1 = input.nextInt();
    System.out.print("Enter second integer: ");
    int n2 = input.nextInt();

    int gcd = 1;//Initial gcd is 1
    int k =2; //Possible gcd
    while(k <= n1 && k <= n2){
      if(n1 % k == 0 && n2 % k == 0){
        gcd = k;//Update gcd
      }
      k++;
    }
    System.out.println("The greatest common divisor for " + n1 + " and" + n2 + " is " + gcd);
  }
}

第二种方法


import java.util.*;
class Main {
  public static void main(String[] args){
    //Create a scanner
    Scanner input = new Scanner(System.in);
    //Prompt the user to enter two integers
    System.out.print("Enter first integer: ");
    int n1 = input.nextInt();
    System.out.print("Enter second integer: ");
    int n2 = input.nextInt();
    int gcd = 1;

    int d = (n1 < n2) ? n1 : n2;//
    for(int i = d; i > 0; i--){
      if(n1 % i == 0 && n2 % i == 0){
        gcd = i;
        break;
      }
    }
    System.out.println("The greatest common divisor for " + n1 + " and " + n2 + " is " + gcd);
  }
}

posted @ 2022-05-19 20:29  Scenery_Shelley  阅读(23)  评论(0)    收藏  举报