Article Directory
Common binary search code is omitted ......
sometimes the next left and upper bounds right, calculating mid, left + right type int would exceed the scope of use
mid = left + (right - left)/2 Instead, to avoid overflow
Calculating approximation root 2, f (x) = x ^ 2; x is incremented between 1-2, using the left and right closed closed interval
1. No. 2 approximation Root
#include<stdio.h>
const double eps = 1e-5;
double f(double x){
return x*x;
}
double calsqrt(){
double left = 1,right = 2,mid;
while((right-left)>eps){
mid = (left+right)/2;
if(f(mid)>2){
right = mid;
} else{
left = mid;
}
}
return mid;
}
int main(){
double k = calsqrt();
printf("%.5f\n",k);
return 0;
}
2. Fast power
Given three integers, A, B, m
A <10 ^. 9
B <10 ^ 18 is
. 1 <m <10 ^. 9
seeking a ^ b% m
1) written recursively
typedef long long LL;
LL binaryPow(LL a, LL b,LL m){
if(b==0) return 1;
if(b%2==1) return a * binaryPow(a,b-1,m);
else{
LL mul = binaryPow(a,b/2,m);
return mul * mul % m;
}
}
2) the wording of Iteration
b writing binary conversion, e.g., 13 = 8 + 4 + 3 + 1 = 2 ^ 2 ^ 2 + 2 ^ 0 = 1101 (binary)
Shilling ans = 1, kanb binary bits whether the end of a, ans as a = ans * a;
then make a = a ^ 2, and b the right that, look as if a tail bit, is a continuing ans = ans * a
loop execution of the step (b just greater than 0)
LL binaryPow1(LL a, LL b,LL m){
LL ans = 1;
while(b>0){
if(b & 1)
ans = ans * a % m;
a = a * a % m;
b >>= 1;
}
return ans;
}