fork(1) download
  1. # Attempt at basic math with limited ops. (5.00)
  2. # Can use:
  3. # Bitwise operations (and, or, xor, not, shift).
  4. # Addition and subtraction by one.
  5. # Negation.
  6. # Comparison against zero.
  7. # @see nHFxFx, UCiqyi
  8.  
  9. def wordsize2s(x, y):
  10. if x == 0 and y == 0:
  11. return 2
  12. return 1 + wordsize2s(abs(x) >> 1, abs(y) >> 1)
  13.  
  14. def to2s(x, n):
  15. m = (1<<n) - 1
  16. y = abs(x) & m
  17. return y if x >= 0 else ((y - 1) ^ m)
  18.  
  19. def from2s(x, n):
  20. m = (1<<n) - 1
  21. x = x & m
  22. s = x >> (n-1)
  23. return x if s == 0 else -((x ^ m) + 1)
  24.  
  25. def unsigned_add(a, b):
  26. if b == 0:
  27. return a
  28. return unsigned_add(a ^ b, (a & b) << 1)
  29.  
  30. # Math public.
  31.  
  32. def flipsign(a, b):
  33. return -a if b < 0 else a
  34.  
  35. def add(a, b):
  36. n = wordsize2s(a, b)
  37. return from2s(unsigned_add(to2s(a, n), to2s(b, n)), n)
  38.  
  39. def sub(a, b):
  40. return add(a, -b)
  41.  
  42. def mul(a, b):
  43. a = flipsign(a, b)
  44. b = abs(b)
  45. if b == 0:
  46. return 0
  47. if b&1 == 0:
  48. return mul(a << 1, b >> 1)
  49. return add(a, mul(a, b - 1))
  50.  
  51. def exp(a, b):
  52. if b < 0:
  53. raise ValueError("domain error")
  54. if b == 0:
  55. return 1
  56. if b&1 == 0:
  57. return exp(mul(a, a), b >> 1)
  58. return mul(a, exp(a, b - 1))
  59.  
  60. # Test.
  61.  
  62. n = 25
  63. for y in range(-n, n):
  64. for x in range(-n, n):
  65. assert add(x, y) == (x + y), "Bad add"
  66. assert sub(x, y) == (x - y), "Bad sub"
  67. assert mul(x, y) == (x * y), "Bad mul"
  68. assert y < 0 or exp(x, y) == (x ** y), "Bad exp"
  69.  
  70. n = 13
  71. for y in range(1, n):
  72. print("".join(format(mul(x, y), "4d") for x in range(1, n)))
Success #stdin #stdout 0.04s 9876KB
stdin
Standard input is empty
stdout
   1   2   3   4   5   6   7   8   9  10  11  12
   2   4   6   8  10  12  14  16  18  20  22  24
   3   6   9  12  15  18  21  24  27  30  33  36
   4   8  12  16  20  24  28  32  36  40  44  48
   5  10  15  20  25  30  35  40  45  50  55  60
   6  12  18  24  30  36  42  48  54  60  66  72
   7  14  21  28  35  42  49  56  63  70  77  84
   8  16  24  32  40  48  56  64  72  80  88  96
   9  18  27  36  45  54  63  72  81  90  99 108
  10  20  30  40  50  60  70  80  90 100 110 120
  11  22  33  44  55  66  77  88  99 110 121 132
  12  24  36  48  60  72  84  96 108 120 132 144