Блог пользователя Surgeon_of_Hell

Автор Surgeon_of_Hell, история, 5 часов назад, По-английски

Problem Statement: Given an integer $$$ n $$$, find the sum of $$$ f(k) $$$, where $$$ f(k) = 1 + 2 + 3 + \ldots + k $$$ and $$$ 1 <= k <= n $$$ . Output the result modulo $$$ 10^9 + 7 $$$. max(n) = $$$10^9$$$.

MY approach: Firstly , very very sorry for my poor english. My approach was to use the formula n(n + 1)/2 in a loop. But I am getting TLE every time. But I don't know how to fix it any further. I first I used 2 nested loops and then only one loop. But not working.

Can some generous person help me?

  • Проголосовать: нравится
  • +13
  • Проголосовать: не нравится

»
5 часов назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Auto comment: topic has been updated by Surgeon_of_Hell (previous revision, new revision, compare).

»
5 часов назад, # |
Rev. 2   Проголосовать: нравится +2 Проголосовать: не нравится

Ok so we're summing this

$$$\displaystyle \sum_{i=1}^n \sum_{j=1}^{i} j$$$

which is

$$$\displaystyle \sum_{i=1}^n \frac{i(i+1)}{2}$$$
$$$\displaystyle = \frac{1}{2} \left ( \sum_{i=1}^n i^2+i \right ) $$$

The sum of

$$$\displaystyle \sum_{i=1}^n i^2=\frac{n(n+1)(2n+1)}{6}$$$

and

$$$\displaystyle \sum_{i=1}^n i=\frac{n(n+1)}{2}$$$

so now the sum is

$$$\displaystyle \frac{1}{2} \left ( \frac{n(n+1)(2n+1)}{6} + \frac{n(n+1)}{2} \right ) $$$

this runs in constant time

some stress test for $k=100$

stress-test
»
5 часов назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Basically, there is a $$$O(1)$$$ solution for this problem. You can convert the problem into the following equation: 1 + (1 + 2) + (1 + 2 + 3) + ... + (1 + 2 + ... + n). Then, solve the equation like this:

$$$ \displaystyle 1 + (1 + 2) + (1 + 2 + 3) + \dots + (1 + 2 + \dots + n) $$$
$$$ \displaystyle = \sum_{i=1}^{n} \sum_{j=1}^{i} j $$$
$$$ \displaystyle = \sum_{i=1}^{n} \frac{i^2 + i}{2} $$$
$$$ \displaystyle = \frac{1}{2} \left( \sum_{i=1}^{n} i^2 + \sum_{i=1}^{n} i \right) $$$
$$$ \displaystyle = \frac{(n^2 + n)(2n + 1)}{12} + \frac{n^2 + n}{4} $$$

And lastly, you must use long long data type instead of int because there are many $$$n^2$$$ terms in the resultant equation.

»
4 часа назад, # |
  Проголосовать: нравится +28 Проголосовать: не нравится