写脚本计算两个正整数的最大公约数
时间: 2024-06-13 22:09:25 浏览: 20
以下是Java语言的两种计算两个正整数最大公约数的例子:
1.使用辗转相除法
```java
public static int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
// 示例
int a = 12, b = 18;
int gcd = gcd(a, b);
System.out.println("最大公约数:" + gcd);
```
2.使用BigInteger类的gcd方法
```java
BigInteger a = new BigInteger("12");
BigInteger b = new BigInteger("18");
BigInteger gcd = a.gcd(b);
System.out.println("最大公约数:" + gcd);
```
相关问题
linux写脚本计算两个正整数的最大公约数
以下是一个Linux脚本计算两个正整数的最大公约数的例子:
```shell
#!/bin/bash
echo "请输入第一个数m:"
read m
echo "请输入第二个数n:"
read n
while [ $n -ne 0 ]
do
r=$(($m % $n))
m=$n
n=$r
done
echo "最大公约数是:$m"
```
写一个python脚本,计算两个列表的笛卡尔积
在Python中,可以使用itertools模块的product函数来计算两个列表的笛卡尔积。
以下是一个简单的示例代码:
```python
import itertools
list1 = ['A', 'B', 'C']
list2 = [1, 2, 3]
# 计算两个列表的笛卡尔积
cartesian_product = list(itertools.product(list1, list2))
# 输出结果
print(cartesian_product)
```
在这个例子中,我们首先定义了两个列表list1和list2。然后,我们使用itertools模块的product函数来计算这两个列表的笛卡尔积,得到一个新的列表cartesian_product。最后,我们将结果输出到控制台。
运行这个脚本,将会输出以下结果:
```
[('A', 1), ('A', 2), ('A', 3), ('B', 1), ('B', 2), ('B', 3), ('C', 1), ('C', 2), ('C', 3)]
```
其中,每个元素都表示一个笛卡尔积的组合。在这个例子中,列表list1中的每个元素都与列表list2中的每个元素组合在一起,得到了9个笛卡尔积的组合。
如果我们要计算多个列表的笛卡尔积,只需要将所有列表作为product函数的参数即可。例如,如果我们要计算三个列表list1、list2和list3的笛卡尔积,可以使用以下代码:
```python
import itertools
list1 = ['A', 'B', 'C']
list2 = [1, 2, 3]
list3 = ['x', 'y']
# 计算三个列表的笛卡尔积
cartesian_product = list(itertools.product(list1, list2, list3))
# 输出结果
print(cartesian_product)
```
运行这个脚本,将会输出以下结果:
```
[('A', 1, 'x'), ('A', 1, 'y'), ('A', 2, 'x'), ('A', 2, 'y'), ('A', 3, 'x'), ('A', 3, 'y'), ('B', 1, 'x'), ('B', 1, 'y'), ('B', 2, 'x'), ('B', 2, 'y'), ('B', 3, 'x'), ('B', 3, 'y'), ('C', 1, 'x'), ('C', 1, 'y'), ('C', 2, 'x'), ('C', 2, 'y'), ('C', 3, 'x'), ('C', 3, 'y')]
```
其中,每个元素都表示一个三元组,表示三个列表的笛卡尔积的组合。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![text/x-java](https://img-home.csdnimg.cn/images/20210720083646.png)
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.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)
![](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)