输入两个正整数m和n,求其最大公约数和最小公倍数

本文介绍了一个简单的Java程序,用于计算两个整数的最大公约数(GCD)和最小公倍数(LCM)。通过迭代的方式找到能同时整除两数的最大数即为最大公约数,并利用公式计算最小公倍数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1 
 2 
 3 import java.io.*;
 4 
 5 public class GCDLCM //GreatestCommonDivisor and LeastCommonMultiple(最大公约数和最小公倍数)
 6 {
 7         public int greatestCD(int m, int n)
 8         {
 9                 int max = 0, gcd = 1;
10                 if(m > n)
11                         max = m;
12                 else
13                         max = n;
14                 for(int i = 1; i <= max; i++)
15                 {
16                         if(m % i == 0 && n % i == 0)
17                         {
18                                 if(i > gcd)
19                                         gcd = i;
20                         }
21                 }
22                 return gcd;
23         }
24         
25         public static void main(String[] args)
26         {
27                 GCDLCM gcdlcm = new GCDLCM();
28                 
29                 String s = "", t = "";
30                 int gcd = 1, lcm = 1, m, n;
31                         
32                 
33                 try 
34                 {
35                         BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
36                         BufferedReader in1 = new BufferedReader(new InputStreamReader(System.in));
37                         s = in.readLine();
38                         t = in1.readLine();
39                 }
40                 catch(IOException e)
41                 {}
42                 
43                 m = Integer.parseInt(s);
44                 n = Integer.parseInt(t);
45                 
46                 //求最大公约数
47                 gcd = gcdlcm.greatestCD(m, n);
48                 //求最小公倍数
49                 lcm = m * n / gcd;
50                 
51                 System.out.println(m + "和" + n + "最大公约数为:" + gcd);
52                 System.out.println(m + "和" + n + "最小公倍数为:" + lcm);
53         }
54 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值