Hacker News new | ask | show | jobs
by edf13 1207 days ago
ChatGPT tells me:

Dividing a number by 7 using bitwise operations can be done using a technique called "magic numbers." This involves precomputing a number that, when combined with bitwise operations, will give the correct result.

Here's how it can be done:

    First, we need to find a "magic number" that will help us divide by 7. One way to do this is to use the fact that 7 is a prime number, which means that there is a number k such that 2^k ≡ -1 (mod 7). This number is called the "multiplicative inverse" of 2 modulo 7. We can find k by repeatedly squaring 2 until we get -1 modulo 7:
lua

2^1 ≡ 2 (mod 7) 2^2 ≡ 4 (mod 7) 2^3 ≡ 1 (mod 7) 2^4 ≡ 2 (mod 7) 2^5 ≡ 4 (mod 7) 2^6 ≡ 1 (mod 7)

So k = 3, since 2^3 ≡ 1 (mod 7).

    Next, we need to combine this magic number with bitwise operations. Specifically, we can use the following formula to divide a number x by 7:
scss

x/7 = (x + (x >> 3)) * k

Here, >> is the bitwise right shift operator, which shifts the bits of x to the right by 3 places, effectively dividing x by 8. The expression (x + (x >> 3)) adds these two values together, which effectively multiplies x by 9. Multiplying by k then gives the correct result of dividing by 7.

Here's some example code in Python that implements this division algorithm:

python

def div_by_7(x): k = 3 return (x + (x >> 3)) * k

Note that this algorithm assumes that the input number x is a non-negative integer. It may not work correctly for negative numbers or floating-point numbers.

1 comments

so... 7/7 = (7+(7>>3))*3 = 21? gotcha
Well it is chat gpt so of course it's confidently incorrect.