XuPengbo
白玉不毁,孰为珪璋

程序设计思维与实践 复习随笔(二)

快速幂运算

typedef long long ll;
ll quick_pow(ll x, ll n, ll mod){
      ll res=1;
      while(n){
        if(n & 1) res = res * x % mod;
        x = x * x % mod;
        n >>= 1;
      }
      return res;
}
typedef long long ll;
ll quick_pow(ll x, ll n, ll mod){
      if(n == 0) return 1;
      ll res = quick_pow(x * x % mod, n / 2, mod);
      if(n & 1) res = res * x % mod; 
      return res;
}

快速乘运算

typedef long long ll;
ll quick_mul(ll a, ll b, ll mod){
      ll res=0;
      while(b){
        if(b & 1) res = (res + a) % mod;
        a = (a + a) % mod;
        b >>= 1;
      }
      return res;
}
typedef long long ll;
ll quick_mul(ll a, ll b, ll mod){
      if(b == 0) return 0;
      ll res = quick_mul((a + a) % mod, b / 2, mod);
      if(b & 1) res = (res + a) % mod; 
      return res;
}

整数二分

升序序列中,找到第一个>=x的位置

int find(int x){
      int l = 1, r = n, ans = -1;
      while(l <= r){
        int mid = (l + r) >> 1;
        if(a[mid] >= x){
          ans = mid;
          r = mid - 1;
        }
        else l= mid + 1;
      }
      return ans;
}

浮点数二分

例如求\(f(x)=x^3+x-2014=0\)的解,小数点精确到5位

double f(double x){ return (pow(x,3)+x-2014); }

eps控制误差法

const double eps = 1e-5;
double find(){
      double l = 1, r = 20;//保证f(l) * f(r)  <0
      while(abs(r - l) > eps){
        double mid = (l + r) / 2;
        if(f(mid) * f(r) <= 0){
          l = mid;
        }
        else r = mid;
      }
      return l;
}
//output:12.6021

迭代次数法

double find(){
      double l = 1, r = 20;//保证f(l) * f(r)  <0
      for(int i=1; i<=20; ++i){
        double mid = (l + r) / 2;
        if(f(mid) * f(r) <= 0){
          l = mid;
        }
        else r = mid;
      }
      return l;
}
//output:12.6021
posted @ 2020-06-26 17:01  XuPengbo  阅读(23)  评论(0)    收藏  举报