Read catalog
- A .O (logn) code for small to prove
- II. Typical time complexity
- III. Common L O G N logN Algorithm
- 1. binary search
- 2. Euclidean algorithm
- 3. exponentiation
- IV. $$ library log function
- Finally, and most important basic
text
A .O (logn) code for small to prove
Let's look at the following piece of code:
int cnt = 1;
while (cnt < n)
{
cnt *= 2;
//时间复杂度为O(1)的程序步骤序列
}
Since cnt after multiplying by 2 each are more close to n, that is, there after x times, thereby cnt will be out of the loop is greater than n, the 2 x = n = n 2x, i.e. x = L O G 2 nx = log2n, so the complexity of this loop is O (logn)
II. Typical time complexity
$c$ 常数
$logN$ 对数级
$log ^ 2N$ 对数平方根
$N$ 线性级
$NlogN$
$N ^ 2$ 平方级
$N ^ 3$ 立方级
$2 ^ N$ 指数级
Thus we can see that, L O G algorithm's efficiency is the highest N logN
III. Common L O G N logN Algorithm
1. binary search
- (int)BinarySearch:(NSArray *)originArray element:(int)element
{
int low, mid, high;
low = 0; high = (int)originArray.count - 1;
while (low <= high) {
mid = (low + high) / 2;
if ([originArray[mid] intValue] < element) {
low = mid + 1;
} else if ([originArray[mid] intValue] > element) {
high = mid -1;
} else {
return mid;
}
}
return -1;
}
2. Euclidean algorithm
- (unsigned int)Gcd:(unsigned int)m n:(unsigned int)n
{
unsigned int Rem;
while (n > 0) {
Rem = m % n;
m = n;
n = Rem;
}
return m;
}
3. exponentiation
- (long)Pow:(long)x n:(unsigned int)n
{
if (n == 0) {
return 1;
}
if (n == 1) {
return x;
}
if ([self isEven:n]) {
return [self Pow:x * x n:n / 2];
} else {
return [self Pow:x * x n:n / 2] * x;
}
}
- (BOOL)isEven:(unsigned int)n
{
if (n % 2 == 0) {
return YES;
} else {
return NO;
}
}
IV. $$ library log function
In $$ Curry log () function and log2 () function
log () function in base default base e of natural logarithm
Base number log2 () function is apparently slightly qwq 2
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
//#define DEBUG(x) cerr << #x << "=" << x << endl
int main()
{
cout << log(M_E) << endl;
cout << log2(2) << endl;
return 0;
}
Then we get
1
1
the result of
$$ Curry and two constants M_E M_PI
M_E represents the natural logarithm base number E
M_PI π represents the circle ratio
Finally, and most important basic
When the subject reaches the data range