使用递归查找 G.C.D 的 Java 程序

javaobject oriented programmingprogramming更新于 2024/4/15 13:00:17

在本文中,我们将了解如何使用递归查找 G.C.D。递归函数是多次调用自身直到满足特定条件的函数。两个数字的最大公约数 (GCD) 是除以它们两个的最大数字。

递归是以自相似方式重复项目的过程。在编程语言中,如果程序允许您在同一函数内调用函数,则称为函数的递归调用。

许多编程语言通过堆栈实现递归。通常,每当一个函数(调用者)调用另一个函数(被调用者)或自身作为被调用者时,调用者函数都会将执行控制权转移给被调用者。此传输过程还可能涉及从调用者传递给被调用者的一些数据。

下面是相同的演示 −

输入

假设我们的输入是 −

输入两个数字:24 和 36

输出

所需的输出将是 −

24 和 36 的最大公约数是 12。

算法

步骤 1 - 开始
步骤 2 - 声明三个值,即 my_input_1、my_input_2 和 my_result
步骤 3 - 从用户那里读取所需值/定义值
步骤 4 - 递归函数‘CommonFactor’ 的定义是接受两个整数作为输入并返回两个值,即 ‘my_input_2’ 值和 ‘my_input_1’ % ‘my_input_2’ 值。
步骤 5 - 该函数被递归调用,直到 ‘my_input_2’ 的值大于 0。存储结果。
步骤 6 - 显示结果
步骤 7 - 停止

示例 1

import java.util.Scanner;
public class GCD {
   public static void main(String[] args) {
      int my_input_1, my_input_2, my_result;
      System.out.println("Required packages have been imported");
      Scanner my_scanner = new Scanner(System.in);
      System.out.println("A reader object has been defined ");
      System.out.print("Enter the first number : ");
      my_input_1 = my_scanner.nextInt();
      System.out.print("Enter the second number : ");
      my_input_2 = my_scanner.nextInt();
      my_result = CommonFactor(my_input_1, my_input_2);
      System.out.printf("The G.C.D of %d and %d is %d.", my_input_1, my_input_2, my_result);
   }
   public static int CommonFactor(int my_input_1, int my_input_2){
      if (my_input_2 != 0)
         return CommonFactor(my_input_2, my_input_1 % my_input_2);
      else
         return my_input_1;
   }
}

输出

Required packages have been imported
A reader object has been defined
Enter the first number : 24
Enter the second number : 36
The G.C.D of 24 and 36 is 12.

示例 2

这里,整数已经被预先定义,并且它的值被访问并显示在控制台上。

public class GCD {
   public static void main(String[] args) {
      int my_input_1, my_input_2, my_result;
      my_input_1 = 24;
      my_input_2 = 36;
      System.out.println("The numbers are defined as " +my_input_1 +" and " +my_input_2);
      my_result = CommonFactor(my_input_1, my_input_2);
      System.out.printf("The G.C.D of %d and %d is %d.", my_input_1, my_input_2, my_result);
   }
   public static int CommonFactor(int my_input_1, int my_input_2){
      if (my_input_2 != 0)
         return CommonFactor(my_input_2, my_input_1 % my_input_2);
      else
         return my_input_1;
   }
}

输出

The numbers is defined as 24 and 36
The G.C.D of 24 and 36 is 12.

相关文章


有用资源