對數複雜度算法

  二分搜索(binary search):給定一個整數X和整數A1,A1,...,AN-1,後者已經預先排序並在內存中,求下標 i 使得 Ai = X,若是X不在數據中,則返回-1。ios

 1 #include <iostream>
 2 #include <vector>
 3 using namespace std;
 4 
 5 const int NOT_FOUND = -1;
 6 template <typename Comparable>
 7 int binarySearch(const vector<Comparable> &a, const Comparable &x) {
 8     int low = 0, high = a.size() - 1;
 9     while(low <= high) {
10         int mid = (low + high) / 2;
11         if(a[mid] < x) {
12             low = mid + 1;
13         } else if(a[mid] > x) {
14             high = mid - 1;
15         } else {
16             return mid;
17         }
18     }
19     return NOT_FOUND;
20 }    //時間複雜度爲O(logN)
21 
22 int main() {
23     vector<int> a;
24     for(int i = 0; i < 20; ++i) {
25         a.push_back(i * 2);
26     }
27     int mid;
28     mid = binarySearch(a, 16);
29     cout << mid << endl;
30     return 0;
31 }

 

歐幾里得算法算法

 1 #include <iostream>
 2 #include <vector>
 3 using namespace std;
 4 
 5 long gcd(long m, long n) {
 6     //歐幾里得算法
 7     //m大於等於n
 8     while(n != 0) {
 9         long rem = m % n;
10         m = n;
11         n = rem;
12     }
13     return m;
14 }    //時間複雜度爲O(logN)
15 
16 int main() {
17     cout << gcd(50, 15) << endl;
18     cout << gcd(1989, 1590) << endl;
19     return 0;
20 }

冪運算:若是N是偶數,XN = XN/2 * XN/2,若是N是奇數,則XN = X(N-1)/2 * X(N-1)/2 * X。spa

 1 #include <iostream>
 2 #include <vector>
 3 using namespace std;
 4 
 5 long pow(long x, int n) {
 6     if(n == 0)
 7         return 1;
 8     if(n == 1) 
 9         return x;
10     if(n%2 == 0)
11         return pow(x * x, n/2); 12     else 
13         return pow(x * x, n/2) * x;
14 }
15 
16 int main() {
17     cout << pow(2, 10) << endl;
18     cout << pow(2, 7) << endl;
19     return 0;
20 }

第11行若替換爲 return pow(pow(x * x, 2), n/2); 或 return pow(pow(x, n/2), 2); ,當n是2時,程序會產生一個無限循環。code

當第11行替換爲 return pow(x, n/2) * pow(x, n/2); 時,會影響程序的效率。blog

相關文章
相關標籤/搜索