1. 程式人生 > >Binary Search and Euclid Algorithm

Binary Search and Euclid Algorithm

#include<iostream> using namespace std;
/*
Performs the standard binary search using two comparisons per level.
Returns index where item is found or -1 if not found.
*/
const int NOT_FOUND = -1;
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;
} /*
Euclid's Algorithm
Euclid's Algorithm for computing the greatest common divisor
*/ long long gcd(long long m, long long n)
{
 while (n != 0)
 {
  long long rem = m%n;
  m = n;
  n = rem;
 }
 return m;
} 歐幾里得演算法的思想
歐幾里得演算法的思想基於輾轉相除法的原理,輾轉相除法是歐幾里得演算法的核心思想,歐幾里得演算法說白了其實就是輾轉相除法的計算機演算法的事項而已。如果gcd(a,b)來表示a和b的最大公約數,那麼根據輾轉相除法的原理,有gcd(a,b)=gcd(b,a mod(b)),其中mod()表示模運算,並且不妨讓a》b這樣方便模運算。
輾轉相除法的正確性gcd(a,b)=gcd(b,a mod(b))的證明:
第一步:令c為a和b的最大公約數,數學符號表示為c=gcd(a,b)。因為任何倆個實數的最大公約數的最大公約數c一定是存在的,也就是說必然存在倆個數k1,k2使得a=k1*c,b=k2*c
第二步:a mod(b)等價於存在整數r,k3使得餘數r=a-k3*b;
 r=a-k3*b=k1*c-k3*k2*c=(k1-k3*k2)c;
 顯然,a和b的餘數r是最大公因數c的倍數。