5 ms·
An easy way to do the second is to consider the sum and the sum of squares. This gets you a-b and a^2-b^2. Recall that the latter is (a-b)(a+b) and the answer f
by nabb 14y ago
An easy way to do the second is to consider the sum and the sum of squares. This gets you a-b and a^2-b^2. Recall that the latter is (a-b)(a+b) and the answer follows immediately.
- drostie 14y agoThat is probably the classiest way I've seen yet to do the second problem. Since I gave Python code above, here it is for your version: >>> from random import shuffle >>> def test(n, missing, extra): ... t = [i if i != missing else extra for i in range(1, n + 1)] ... shuffle(t) ... return t ... >>> def solve(list): ... diff, diffsq, n = 0, 0, 1 ... for i in list: ... diff += i - n ... diffsq += i*i - n*n ... n += 1 ... sum = diffsq / diff ... return {'extra': (sum + diff)/2, 'missing': (sum - diff)/2} ... >>> solve(test(7633507, missing=3518688, extra=4057456)) {'missing': 3518688L, 'extra': 4057456L}