编写两个函数,其功能分别为: ⑴ 求N个整数的次大值和次小值 ⑵ 求两个整数的最大公约数和最小公倍数
时间: 2023-09-22 14:06:55 浏览: 120
C语言程序设计-求出两个非零正整数的最大公约数,并作为函数值返回
5星 · 资源好评率100%
⑴ 求N个整数的次大值和次小值:
```python
def find_second_largest_smallest(numbers):
# 求次大值
largest = second_largest = float('-inf')
for num in numbers:
if num > largest:
second_largest = largest
largest = num
elif num > second_largest and num != largest:
second_largest = num
# 求次小值
smallest = second_smallest = float('inf')
for num in numbers:
if num < smallest:
second_smallest = smallest
smallest = num
elif num < second_smallest and num != smallest:
second_smallest = num
return second_largest, second_smallest
```
⑵ 求两个整数的最大公约数和最小公倍数:
```python
def gcd_lcm(a, b):
# 求最大公约数
def gcd(x, y):
while y:
x, y = y, x % y
return x
# 求最小公倍数
def lcm(x, y):
return x * y // gcd(x, y)
return gcd(a, b), lcm(a, b)
```
阅读全文