编写一个方法用于求任意两个正藝数的最大公约数,调用此方法求10和25的最大公约数,用Java代码写出来
时间: 2024-04-29 15:27:11 浏览: 8
以下是Java代码:
```
public class Main {
public static void main(String[] args) {
int num1 = 10;
int num2 = 25;
int gcd = findGCD(num1, num2);
System.out.println("10和25的最大公约数为:" + gcd);
}
public static int findGCD(int num1, int num2) {
if (num2 == 0) {
return num1;
}
return findGCD(num2, num1 % num2);
}
}
```
相关问题
编写一个方法用于求任意两个整数的最大公约数调用此方法求10和25的最大公约数
求解:
10和25的最大公约数为5。
方法如下:
public static int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
调用该方法:
int result = gcd(10, 25);
最终得到的结果为5。
用c语言编写函数求出任意两个正整数的最大公约数和最小公倍数。在主函数中输入这两个数
好的,以下是C语言的函数代码:
```c
#include <stdio.h>
int gcd(int a, int b) { // 求最大公约数
return b == 0 ? a : gcd(b, a % b);
}
int lcm(int a, int b) { // 求最小公倍数
return a * b / gcd(a, b);
}
int main() {
int a, b;
printf("请输入两个正整数:");
scanf("%d %d", &a, &b);
printf("它们的最大公约数为:%d\n", gcd(a, b));
printf("它们的最小公倍数为:%d\n", lcm(a, b));
return 0;
}
```
使用时,可以直接调用 `gcd` 函数和 `lcm` 函数分别求解最大公约数和最小公倍数。在 `main` 函数中,使用 `scanf` 函数输入两个整数,然后输出结果即可。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)