Write a function that computes
Submit
Note that you don't need a really good computer to make this computation, it should take less than a second.
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.
The idea is to use Beatty Sequence to simplify computation. Given r 1 + s 1 = 1 , ⌊ s ∗ i ⌋ and ⌊ r ∗ i ⌋ partitions the set of positive integers, for positive integer i . Hence we have:
S ( n , r ) = 2 e ( e + 1 ) − S ( n ′ , s ) , e = ⌊ n r ⌋ , n ′ = ⌊ s e ⌋
Now if 1 < r < 2 , n ′ will be pretty small relative to n . Since S ( n , r + k ) = k 2 n ( n + 1 ) + S ( n , r ) if k is an integer, we can form the following recursion:
S ( n , r ) r 0 e 1 = r 0 2 n ( n + 1 ) + S ( n , r 1 ) = r 0 2 n ( n + 1 ) + 2 e 1 ( e 1 + 1 ) − S ( n 1 , s 1 ) = ⌊ r ⌋ − 1 , r 1 = r − r 0 = ⌊ n r 1 ⌋ , n 1 = ⌊ s 1 e 1 ⌋ , s 1 = 1 − 1 − r 1 1
This ensures that n 1 is always significantly smaller than n , and hence drastically speed up the computation of the recursion. For accuracy, this can be implemented in sympy. The implementation is below and it takes ~30s to solve.
But we can do way better. We can implement the symbolic calculations only with integers and no floats to preserve precision. We can also calculate rational approximations to r to the precision we need, store the result, and only calculate to higher precisions when we need to, and remove all recursions (Python has huge overhead in recursion). This results in a 4000x speedup, calculating the answer in only 0.0089s. The implementation is also below. Below I also calculate for larger n = 1 0 1 0 0 0 and n = 1 0 1 0 0 0 0 . Do note I'm using python 3.8 here, which is required for
math.comb
.