使用递归计算指定数字的 GCD 的 Java 程序
可以使用递归来计算给定的两个数字的 GCD,如下面的程序所示。
示例
import java.util.Scanner; public class GCDUsingRecursion { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter first number :: "); int firstNum = sc.nextInt(); System.out.println("Enter second number :: "); int secondNum = sc.nextInt(); System.out.println("GCD of given two numbers is ::"+gcd(firstNum, secondNum)); } public static int gcd(int num1, int num2) { if (num2 != 0){ return gcd(num2, num1 % num2); } else{ return num1; } } }
输出
Enter first number :: 625 Enter second number :: 125 GCD of given two numbers is ::125
广告