Programming challenge #10 has been posted at dev102.com.
If all the numbers 1..n were present, then they would sum to n(n+1)/2. If some x is absent, then they will sum to n(n+1)/2 - x. So to determine which number is missing, subtract the sum of the series from the expected sum.
This python code finds the missing number in the series named values:
def test(values) : max_val = len(values) + 1 expected_sum = max_val*(max_val + 1) / 2 return expected_sum - sum(values)
Here is a complete test:
import random def test(values) : max_val = len(values) + 1 expected_sum = max_val*(max_val + 1) / 2 return expected_sum - sum(values) test_range = 200 for i in range(1,test_range) : a = range(1, i) + range(i+1, test_range+1) random.shuffle(a) x = test(a) if x != i : print "Failed at ", i print a print sum(a) break

Leave a comment