编写一程序,求两个整数的最大公约数
时间: 2024-05-08 19:15:08 浏览: 13
以下是Python语言的程序:
```python
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
a = int(input("请输入第一个整数:"))
b = int(input("请输入第二个整数:"))
result = gcd(a, b)
print("最大公约数为:", result)
```
运行结果示例:
```
请输入第一个整数:24
请输入第二个整数:36
最大公约数为: 12
```
相关问题
使用c语言编写程序求两个整数的最大公约数。
好的,可以使用欧几里得算法(辗转相除法)来求解两个整数的最大公约数。以下是C语言代码实现:
```c
#include <stdio.h>
int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
int main() {
int a, b;
printf("请输入两个整数: ");
scanf("%d %d", &a, &b);
int result = gcd(a, b);
printf("最大公约数为: %d\n", result);
return 0;
}
```
在以上代码中,`gcd`函数使用递归的方式实现了欧几里得算法,当`b`为0时,`a`即为最大公约数。在`main`函数中,先输入两个整数,然后调用`gcd`函数求解最大公约数,并输出结果。
编写程序求两整数的最大公约数
下面是一个求两个整数的最大公约数(GCD)的 C 语言程序:
```c
#include <stdio.h>
int gcd(int a, int b) {
int temp;
while (b != 0) {
temp = b;
b = a % b;
a = temp;
}
return a;
}
int main() {
int num1, num2, result;
printf("请输入两个整数:");
scanf("%d %d", &num1, &num2);
result = gcd(num1, num2);
printf("最大公约数是:%d\n", result);
return 0;
}
```
这个程序定义了一个名为 `gcd` 的函数来计算两个整数的最大公约数。函数使用了欧几里得算法(也称为辗转相除法)来计算最大公约数。程序从用户输入两个整数开始,调用 `gcd` 函数来计算它们的最大公约数,并将结果输出到屏幕上。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)