Skip to content

Instantly share code, notes, and snippets.

@Rudxain
Last active December 19, 2022 06:41
Show Gist options
  • Save Rudxain/fbea0914f7b994ed51a370bb3686f206 to your computer and use it in GitHub Desktop.
Save Rudxain/fbea0914f7b994ed51a370bb3686f206 to your computer and use it in GitHub Desktop.
Special-cased algorithm to divide by 2 in base 10. With a hint to an extended version that works on arbitrary radix

divide each digit by 2 starting from the MSD using int div, if you have remainder it means you have to add 5 to the next digit AFTER dividing it by 2.

Examples:

  1. 1687
  2. 1/2 = 0, carry 5 because odd
  3. 6/2 = 3, 3+5 = 8
  4. 8/2 = 4
  5. 7/2 = 3, carry 5
  6. 0/2 = 0, 0+5 = 5

result is: 843.5

This algorithm could be extended to other bases/radices: Whenever you want to divide a radix B numeral by d, and d is a factor of B, the extended algorithm can speed-up division. The actual implementation is left as an excercise to the reader ;) lol

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment