1.最大公约数
分为递归写法和迭代写法
(1)递归(建议写这个)
cpp
int gcd(int a, int b) {
if (b == 0) return a; // 终止条件:b=0时,a为最大公约数
return gcd(b, a % b); // 递归调用:gcd(b, a mod b)
}
(2)迭代
cpp
int gcd(int a, int b) {
a = abs(a); // 处理负数
b = abs(b);
while (b != 0) { // 循环条件:b不为0
int temp = b; // 临时保存b
b = a % b; // 更新b为a mod b
a = temp; // 更新a为原b
}
return a; // 当b=0时,a即为GCD
}
还有要注意要先拿一个数储存gcd(最大公约数)不然后面可能gcd会变
可以写这一题试试
下面是我的答案
cpp
#include <algorithm>
using namespace std;
int gcd(int a,int b)
{ if(b==0)return a;
return gcd(b,a%b);
}
int main()
{ int a,b,c,Min,Max;
cin>>a>>b>>c;
Min=min({a,b,c});
Max=max({a,b,c});
//cout<<gcd(Min,Max)<<endl;
int gcd1=gcd(Min,Max);
Min/=gcd1;//Min改了下面的gcd也改了
Max/=gcd1;
//cout<<gcd(Min,Max)<<endl;
cout<<Min<<"/"<<Max;
}
2.二分查找
cpp
#include <iostream>
#include <vector>
using namespace std;
// 二分查找函数
int binarySearch(const vector<int>& arr, int target) {
int left = 0;
int right = arr.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2; // 计算中间位置
if (arr[mid] == target) {
return mid; // 找到目标元素,返回索引
} else if (arr[mid] < target) {
left = mid + 1; // 目标元素在右半部分
} else {
right = mid - 1; // 目标元素在左半部分
}
}
return -1; // 未找到目标元素,返回 -1
}
int main() {
vector<int> sortedArray = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
int target = 7;
int result = binarySearch(sortedArray, target);
if (result != -1) {
cout << "Element found at index: " << result << endl;
} else {
cout << "Element not found in the array." << endl;
}
return 0;
}
注意二分查找一定要是排好顺序的数组(可以先用下面的冒泡排序)
为什么用int mid = left + (right - left) / 2; // 计算中间位置
而不用(left+right)/2
使用 `int mid = left + (right - left) / 2` 而不是 `(left + right) / 2` 有几个好处,尤其是在实现二分搜索时:
-
**避免溢出**:如果 `left` 和 `right` 是非常大的整数,`left + right` 可能导致整数溢出,特别是对于 32 位整数系统。`left + (right - left) / 2` 避免了这种风险,因为它不会超出整数范围。
-
**确保中间值合理**:即使在非溢出的情况下,`left + (right - left) / 2` 也能保证结果始终是 `[left, right]` 范围内的有效索引,尤其在 `left` 和 `right` 的值非常接近时。
-
**兼容性**:这种写法在某些旧的或者不同的编程语言和环境中更安全,因为它们可能没有现代的溢出保护机制。
因此,`left + (right - left) / 2` 是一种更 robust 和安全的计算中间位置的方法。
3.冒泡排序
cpp
#include <iostream>
#include <vector>
using namespace std;
// 冒泡排序函数
void bubbleSort(vector<int>& arr) {
int n = arr.size();
bool swapped;
for (int i = 0; i < n - 1; i++) {
swapped = false;
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr[j], arr[j + 1]); // 交换相邻元素
swapped = true;
}
}
if (!swapped) {
break; // 如果没有发生交换,说明数组已经有序
}
}
}
int main() {
vector<int> unsortedArray = {64, 34, 25, 12, 22, 11, 90};
cout << "Unsorted Array: ";
for (int num : unsortedArray) {
cout << num << " ";
}
cout << endl;
bubbleSort(unsortedArray);
cout << "Sorted Array: ";
for (int num : unsortedArray) {
cout << num << " ";
}
cout << endl;
return 0;
}