{"id":16312139,"url":"https://github.com/shlomif/shift_divmod","last_synced_at":"2025-04-14T22:48:14.209Z","repository":{"id":57466777,"uuid":"294941690","full_name":"shlomif/shift_divmod","owner":"shlomif","description":"Optimized bigint divmod implementations for division bases that have a large number of trailing 0 bits.","archived":false,"fork":false,"pushed_at":"2021-12-24T08:23:52.000Z","size":77,"stargazers_count":1,"open_issues_count":0,"forks_count":1,"subscribers_count":3,"default_branch":"master","last_synced_at":"2024-10-11T09:21:07.457Z","etag":null,"topics":["gmp","hacktoberfest","math","mathematics","modulus"],"latest_commit_sha":null,"homepage":"https://pypi.org/project/shift-divmod/","language":"C","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/shlomif.png","metadata":{"files":{"readme":"README.rst","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2020-09-12T12:42:17.000Z","updated_at":"2021-12-24T08:23:55.000Z","dependencies_parsed_at":"2022-09-10T08:23:08.671Z","dependency_job_id":null,"html_url":"https://github.com/shlomif/shift_divmod","commit_stats":null,"previous_names":[],"tags_count":6,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shlomif%2Fshift_divmod","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shlomif%2Fshift_divmod/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shlomif%2Fshift_divmod/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shlomif%2Fshift_divmod/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/shlomif","download_url":"https://codeload.github.com/shlomif/shift_divmod/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248975299,"owners_count":21192199,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["gmp","hacktoberfest","math","mathematics","modulus"],"created_at":"2024-10-10T21:46:52.645Z","updated_at":"2025-04-14T22:48:14.161Z","avatar_url":"https://github.com/shlomif.png","language":"C","readme":"==============================================================================\nShiftDivMod.  Implement faster divmod() for moduli with trailing 0 bits\n==============================================================================\n:Info: This is the README file for ShiftDivMod.\n:Author: Shlomi Fish \u003cshlomif@cpan.org\u003e\n:Copyright: © 2020, Shlomi Fish.\n:Date: 2020-09-20\n:Version: 0.4.3\n\n.. index: README\n.. image:: https://travis-ci.org/shlomif/shift_divmod.svg?branch=master\n   :target: https://travis-ci.org/shlomif/shift_divmod\n\nPURPOSE\n=======\n\nThis distribution implements faster divmod() (and ``.mod()``) operations\nfor moduli with a large number of trailing 0 bits (where the div/mod base\nis divisible by ``2 ** n`` for an integer `n`).\n\nIt should yield the same result as the built-n divmod() function for\npositive numerators (its behaviour for negative ones is currently\nuntested and undefined).\n\nAlso provided is a port to C and gmplib (= GNU multiple precision):\nhttps://github.com/shlomif/shift_divmod/tree/master/gmp-shift_divmod\n\nINSTALLATION\n============\n\npip3 install shift_divmod\n\nUSAGE\n=====\n\n::\n\n    from shift_divmod import ShiftDivMod\n\n    base = 997\n    shift = 1200\n    modder = ShiftDivMod(base, shift)\n    # Alternative constructor which may require more\n    # work and eventualy calls the default constructor\n    modder = ShiftDivMod.from_int(base \u003c\u003c shift)\n\n    x = 10 ** 500\n    # Same as divmod(x, (base \u003c\u003c shift))\n    print( modder.divmod(x) )\n\nNOTES\n=====\n\nThe code from which this distribution has been derived, was proposed as a\nproof-of-concept for a potential improvement for the built in cpython3\noperations here: https://bugs.python.org/issue41487 . However, changing cpython3\nin this manner was rejected.\n\nlibdivide ( https://github.com/ridiculousfish/libdivide ) provides a\ndifferent, but also interesting, approach for optimizing division.\n\nBENCHMARKS:\n===========\n\nOn my system, I got these results after running\n``python3 code/examples/shift_divmod_example.py bench`` (reformated\nfor clarity):\n\n::\n\n    {'val': 5206685, 'time': 38.86349368095398, 'reached': 1000,\n     'interrupted': False, 'mode': 'gen_shift_mod'}\n    {'val': 5206685, 'time': 39.018390417099, 'reached': 1000,\n     'interrupted': False, 'mode': 'shiftmodpre'}\n    {'val': mpz(5206685), 'time': 167.4433994293213, 'reached': 1000,\n     'interrupted': False, 'mode': 'gmpy'}\n    {'val': 3346424, 'time': 229.94409656524658, 'reached': 25,\n     'interrupted': True, 'mode': 'builtinops'}\n\n    System:    Kernel: 5.8.8-200.fc32.x86_64 x86_64 bits: 64\n        Desktop: KDE Plasma 5.18.5\n               Distro: Fedora release 32 (Thirty Two)\n    CPU:       Info: Quad Core model: Intel Core i5-8259U\n        bits: 64 type: MT MCP L2 cache: 6144 KiB\n               Speed: 1600 MHz min/max: 400/3800 MHz Core speeds (MHz):\n                    1: 1600 2: 1600 3: 1601\n               4: 1600 5: 1600 6: 1601 7: 1601 8: 1601\n    Graphics:  Device-1: Intel Iris Plus Graphics 655 driver: i915 v: kernel\n               Display: server: Fedora Project\n               X.org 1.20.8 driver: modesetting unloaded: fbdev,vesa\n               resolution: 1920x1080~60Hz\n               OpenGL: renderer: Mesa Intel Iris Plus\n               Graphics 655 (CFL GT3) v: 4.6 Mesa 20.1.7\n\nAs can be noticed the shift_divmod based versions are over 4 times faster than\nGMP and much faster than the builtinops which only completed 25 out of 1,000 iterations\nbefore being interrupted. Note that for that use case, using GMP's modular exponentiation\nseems even faster.\n\nWith the C and gmplib version:\n\n- ``mpz_mod`` runs the benchmark in about 160 seconds.\n- ``shift_divmod`` runs the benchmark in about 35 seconds.\n- ``pypy3`` runs the pure-Python code in 25 seconds (!).\n\nThe Secret Sauce:\n-----------------\n\nThe code utilises the fact that `bitwise operations \u003chttps://en.wikipedia.org/wiki/Bitwise_operation\u003e`_\nare fast, and the magic happens in this code (with some comments added for clarity):\n\n::\n\n    # Precalculating the object's field so that:\n    # self.shift : a non-negative integer signifying the bit shift\n    # self.base  : a non-negative integer which is shifted to\n    # form the modulu\n    # self.n = self.base \u003c\u003c self.shift\n    # self.mask = ((1 \u003c\u003c self.shift) - 1)\n    def divmod(self, inp):\n        \"\"\"calculate divmod(inp, self.n)\"\"\"\n        if inp \u003c self.n:\n            return 0, inp\n        div, mod = divmod((inp \u003e\u003e self.shift), self.base)\n        return div, ((mod \u003c\u003c self.shift) | (inp \u0026 self.mask))\n\n(Or the equivalent but more bureaucratic C and gmplib code.)\n\nCOPYRIGHT\n---------\nCopyright © 2020, Shlomi Fish.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n1. Redistributions of source code must retain the above copyright\n   notice, this list of conditions, and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright\n   notice, this list of conditions, and the following disclaimer in the\n   documentation and/or other materials provided with the distribution.\n\n3. Neither the name of the author of this software nor the names of\n   contributors to this software may be used to endorse or promote\n   products derived from this software without specific prior written\n   consent.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fshlomif%2Fshift_divmod","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fshlomif%2Fshift_divmod","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fshlomif%2Fshift_divmod/lists"}