examples.k 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. \l bigint.k
  2. / -- (not (n base 2)) ~ ((127 - n) base 2) for all base 127 digits n --
  3. `0:"-- use subtraction to not bits --"
  4. ~/(~2\!128;2\127-!128)
  5. / -- bigints use lists of digits --
  6. / Signed 7-bit numbers use the most significant bit for the signed bit
  7. / negation uses twos complement
  8. `0:"-- twos complement --"
  9. +2\*'(,59; \neg[,59])
  10. / -- since we're base 128, numbers which use the 7th bit need a leading zero --
  11. / to provide a signed bit.
  12. `0:"-- extra digit for signed bit --"
  13. ,/'+'2\'(0 69; \neg 0 69)
  14. / -- double negation is the identity --
  15. `0:"-- negation is own inverse --"
  16. neg neg[,69]
  17. neg neg[0 69]
  18. / -- for unsigned base 128 bigints, extra digit is not needed --
  19. `0:"-- unsigned addition --"
  20. add[,69;72]
  21. / -- signed addtion follows the convention above --
  22. `0:"-- signed addition --"
  23. adds[,69;,72]
  24. / -- Handling the signed bit is tricky --
  25. / test cases
  26. #T:,/,/:\:/2#,,',/1 neg'\T0:,/1(+|1(0 127@64>)\)\12 63 121
  27. / convert to integers
  28. c:{(-1 1s)*128/((neg;::)@s:64>*x)x}
  29. / test that digit-wise addition matches addition
  30. / covers (all?) the odd sign bit cases
  31. `0:"-- addtion test --"
  32. ~/(+/'c''T;c'adds.'T)
  33. / divisor times all positive digits base 128
  34. `0:"-- Render base 10 --"
  35. ms:128\'10*1_!128
  36. ($n)~ \,/$|*|(#*:){(!0;*|x),' \divmod[ms;*x]}/( \128\n:72932651;!0)