Problem 532382 · hard · Phase 05 Advanced Algorithms & Graphs

Ribbons on the Numbered Fence Posts

number theory · divisors · floor division blocks · arithmetic series

A very long fence has posts numbered 1, 2, 3, .... For every whole number d >= 1 there is a decorator number d, who walks along the fence and ties exactly d ribbons on every post whose number is a multiple of d. So post 6 receives 1 + 2 + 3 + 6 = 12 ribbons.

Return the total number of ribbons on the posts numbered lo to hi inclusive.

Examples

Input:  lo = 1, hi = 6
Output: 33
Explanation: posts 1..6 get 1, 3, 4, 7, 6 and 12 ribbons.
Input:  lo = 4, hi = 4
Output: 7
Explanation: decorators 1, 2 and 4 visit post 4.

Constraints

  • 1 <= lo <= hi <= 10**10
  • Return the exact integer (it can exceed 10**19).
  • Visiting posts one by one, or decorators one by one, is far too slow at the largest sizes.

Goals

  • Swap a sum over posts and their divisors into a sum over divisors and their multiples
  • Group the values d that share the same floor(n / d) into one block
  • Sum a block of consecutive d with the arithmetic series formula
Starting Python…