fork download
  1. def binaryDivision(int a, int b) {
  2. int result = 0
  3. int sign = 0
  4. if (a < 0) {
  5. sign = sign + 1
  6. a = 0 - a
  7. }
  8. if (b < 0) {
  9. sign = sign - 1
  10. b = 0 - b
  11. }
  12.  
  13. int limit = a >> 1
  14. if (limit < (1 << 30)) limit = 1 << 30
  15. int origB = b
  16. while (b < limit) {
  17. b = b << 1
  18. }
  19. while (b >= origB) {
  20. result = result << 1
  21. if (a >= b) {
  22. a = a - b
  23. result = result + 1
  24. }
  25. b = b >> 1
  26. }
  27.  
  28. if (sign != 0) result = 0 - result
  29. return result
  30. }
  31.  
  32. 100000.times {
  33. def RNG = new Random()
  34. int a = RNG.nextInt()
  35. int b = RNG.nextInt()
  36. int expected = a/b
  37. //println "$a $b"
  38. assert binaryDivision(a, b) == expected
  39. }
  40.  
  41. int divBy10(int x) {
  42. int result = 214748364
  43. for (int i = 32; i > 0; i = i - 1) {
  44. if (x & 1) {
  45. //Integer.parseInt('00011001100110011001100110011001', 2)
  46. result = result + 429496729
  47. }
  48. x = x >> 1
  49. result = result >> 1
  50. }
  51. return result
  52. }
  53.  
  54. 100000.times {
  55. assert divBy10(it) == (it / 10 as int)
  56. }
  57.  
Success #stdin #stdout 2.64s 333376KB
stdin
Standard input is empty
stdout
Standard output is empty