Project Euler Problem 760

Define where oplus, vee, wedge are the bitwise XOR, OR and AND operator respectively.

Project Euler Problem 760

Solution

Answer: 172747503

We use the identity

$$(m\vee n)=(m\oplus n)+(m\wedge n),$$

so

$$g(m,n) =(m\oplus n)+(m\vee n)+(m\wedge n) =2\bigl((m\oplus n)+(m\wedge n)\bigr) =2(m\vee n).$$

Therefore

$$G(N)=2\sum_{\substack{a,b\ge0\a+b\le N}}(a\vee b).$$

Now evaluate the sum bit-by-bit.

For a fixed bit $p$, its contribution is $2^{p+1}$ times the number of ordered pairs $(a,b)$ with

$$a+b\le N$$

for which bit $p$ of $a\vee b$ is $1$.

Let

$$T=\frac{(N+1)(N+2)}2$$

be the total number of ordered pairs $(a,b)$ with $a+b\le N$.

If $C_p$ is the number of such pairs with both $p$-th bits equal to $0$, then the number with OR-bit $1$ is $T-C_p$.

Hence

$$G(N)=\sum_{p\ge0} 2^{p+1}(T-C_p).$$

A standard binary digit-DP over the equation

$$a+b+c=N$$

(with $c\ge0$) computes each $C_p$ efficiently in $O(\text{bits})$.

Running the computation for

$$N=10^{18}$$

gives

$$G(10^{18}) \equiv 172747503 \pmod{1,000,000,007}.$$

Answer: 172747503