二分搜索&最大公因數

二分搜索

/**
*Performs the standard binary search using two comparisons per level
*Return index where item is found or -1 id not found.
*/
template <typename Comparable>
int binarySearch(const vector<Comparable> & a,const Comparable & x)
{
     int low=0,high=a.size()-1;
     while(low <=high)
    {
      int mid=(low+high)/2;
      if(a[mid]<x)
        low=mid+1;
      else if( a[mid] >x)
        high=mid-1;
      else
          return mid; //Found
    }
   return NOT_FOUND   //NOT_FOUND is defined as -1
}

最大公因數(歐幾里得算法)

long gcd(long m,long n)
{
   while(n!=0)
   {
     long rem=m%n;
     m=n;
     n=rem;
   }
   return m;
}

高效率的冪運算

long pow(long x, int n)
{
   if (n ==0 )
        return 1;
   if( n == 1)
         return x;
   if( isEven(n))
        retrun pow(x*x,n/2);
   else
        retrun pow(x*x,n/2)*x;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章