Guest User

Untitled

a guest
Mar 18th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.89 KB | None | 0 0
  1. static bool coprime(long u, long v)
  2. {
  3. if (((u | v) & 1) == 0) return false;
  4.  
  5. while ((u & 1) == 0) u >>= 1;
  6. if (u == 1) return true;
  7.  
  8. do
  9. {
  10. while ((v & 1) == 0) v >>= 1;
  11. if (v == 1) return true;
  12.  
  13. if (u > v) { long t = v; v = u; u = t; }
  14. v -= u;
  15. } while (v != 0);
  16.  
  17. return false;
  18. }
  19.  
  20. template<class T>
  21. inline T gcd(T a, T b) {
  22. while(b) {
  23. auto t = a % b;
  24. a = b;
  25. b = t;
  26. }
  27. return a;
  28. }
  29.  
  30. template<class T>
  31. inline bool are_coprimes(T a, T b) {
  32. if(!((a | b) & 1))
  33. return false; // Both are even numbers, divisible by at least 2.
  34. return 1 == gcd(a, b);
  35. }
  36.  
  37. inline unsigned gcd(unsigned u, unsigned v)
  38. {
  39. auto shift = __builtin_ctz(u | v);
  40. u >>= __builtin_ctz(u);
  41. do {
  42. v >>= __builtin_ctz(v);
  43. if(u > v)
  44. std::swap(u, v);
  45. } while((v -= u));
  46. return u << shift;
  47. }
Add Comment
Please, Sign In to add comment