Let the function Θ ( n ) denote the sum of all natural numbers less than or equal to n . However, this function has one trick - if the number to be added i is a power of 2 (i.e 2 x ≡ i ), then instead of adding, we subtract the number.
What is i = 4 ∑ 1 0 0 0 0 Θ ( i ) ?
As an explicit example, Θ ( 4 ) = − 4 .
This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try
refreshing the page, (b) enabling javascript if it is disabled on your browser and,
finally, (c)
loading the
non-javascript version of this page
. We're sorry about the hassle.
As Brian Riccardi noted, there is a formula for Θ ( n ) . This in turn implies a formula for a sum of Θ ( n ) . If we define M ( n ) = ⌊ lo g 2 n ⌋ , then Θ ( n ) n = 1 ∑ N Θ ( n ) = = = = j = 1 ∑ n j − 2 2 j ≤ n ∑ 2 j = 2 1 n ( n + 1 ) − 2 j ≤ n ∑ 2 j + 1 6 1 N ( N + 1 ) ( N + 2 ) − n = 1 ∑ N 2 j ≤ n ∑ 2 j + 1 6 1 N ( N + 1 ) ( N + 2 ) − j = 0 ∑ M ( N ) ( N + 1 − 2 j ) 2 j + 1 6 1 N ( N + 1 ) ( N + 2 ) − 2 ( N + 1 ) ( 2 M ( N ) + 1 − 1 ) + 3 2 ( 4 M ( N ) + 1 − 1 ) The difference between the value of this expression for N = 1 0 0 0 0 and N = 3 is 1 6 6 5 6 7 9 3 4 2 0 8 . No programming is necessary, only computation.
\text{\$\theta(n)=(\displaystyle\sum\_{k=1}^{n}k)-2(\displaystyle\sum_{k=1}^{\lfloor log_2(n) \rfloor}2^k)=\frac{n(n+1)}{2} -2(2^{\lfloor log_2(n) \rfloor+1}-1)\$} \\
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|
1 2 3 4 5 6 7 |
|
The python 3:
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Noticing that N ≤ 1 0 0 0 0 , it will take less than a minute even with an O ( n 2 ) algorithm. While one could design a more efficient algorithm, it's easiest to just brute force this one
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
Problem Loading...
Note Loading...
Set Loading...
Using the simple mathematical equation for arithmetic progressions:
S ( n ) = 2 n ( n + 1 ) , we can create a sum function that adds all natural numbers less than or equal to n.
Then in the main function: