intalgo.c 864 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #include "precompile.h"
  2. #include "intalgo.h"
  3. TOOLKIT_API int gcd(int x1, int x2)
  4. {
  5. int n;
  6. if (x1 < 0) x1 = -x1;
  7. if (x2 < 0) x2 = -x2;
  8. if (x1 > x2) {
  9. n = x1;
  10. x1 = x2;
  11. x2 = n;
  12. }
  13. while (x2) {
  14. n = x1 % x2;
  15. x1 = x2;
  16. x2 = n;
  17. }
  18. return x1;
  19. }
  20. TOOLKIT_API int cprime(int n)
  21. {
  22. int p , q , r;
  23. if(n <= 2) return 2;
  24. if(n <= 3) return 3;
  25. if(! (n & 1)) n++;
  26. while (1) {
  27. p = 3;
  28. q = n - 3;
  29. r = 9;
  30. while(q % p) {
  31. p++;
  32. r += (p << 2);
  33. q -= 2;
  34. if(r > n) return n;
  35. p++;
  36. }
  37. n += 2;
  38. }
  39. }
  40. TOOLKIT_API int isqrt(unsigned N)
  41. {
  42. unsigned l2, u, v, u2, n;
  43. if(2 > N) {
  44. return N;
  45. }
  46. u = N;
  47. l2 = 0;
  48. /* 1/2 * log_2 N = highest bit in the result */
  49. while((u >>= 2)) {
  50. l2++;
  51. }
  52. u = 1L << l2;
  53. v = u;
  54. u2 = u << l2;
  55. while(l2--) {
  56. v >>= 1;
  57. n = (u + u + v) << l2;
  58. n += u2;
  59. if(n <= N) {
  60. u += v;
  61. u2 = n;
  62. }
  63. }
  64. return u;
  65. }