Effective implementation of algorithms (Master Thesis)
Effective and error-free implementation of algorithms
src/math/gcd/gcd.h
Go to the documentation of this file.
00001 #ifndef H_MATH_GCD_GCD
00002 #define H_MATH_GCD_GCD
00003 
00004 #include <algorithm>
00005 #include <limits>
00006 #include "utils/branch_predict/branch_predict.h"
00007 #include <stdexcept>
00008 
00009 namespace math {
00010 namespace gcd {
00011 
00012 
00013 template<typename T>
00014   T gcd(T a, T b) {
00015     // fix the negative values
00016     if (std::numeric_limits<T>::is_signed && a < 0) {
00017       if (UNLIKELY(a == std::numeric_limits<T>::min())) {
00018         throw std::overflow_error("problem calculating gcd - big negative number");
00019       }
00020       a = -a;
00021     }
00022     if (std::numeric_limits<T>::is_signed && b < 0) {
00023       if (UNLIKELY(b == std::numeric_limits<T>::min())) {
00024         throw std::overflow_error("problem calculating gcd - big negative number");
00025       }
00026       b = -b;
00027     }
00028 
00029     // Warning: std::__gcd works only with positive values
00030     // Note: std::__gcd is for internal use, but we do not want to reimplement
00031     // already implemented things
00032     return std::__gcd(a, b);
00033   }
00034 
00035 } // namespace gcd
00036 } // namespace math
00037 #endif
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Defines