Q:

Calculate missing number

Here's the exercise:

You have been given a list of sequential numbers from 1 to 10,000, but
  they are all out of order; furthermore, a single number is missing
  from the list. The object of the task is to find out which number is
  missing.

The strategy to this problem is to sum the elements in the array, then sum the range 1 to 10,000, and subtract the difference. This is equal to the missing number. The formula for calculating the sum of the range from 1..n being n(n+1)/2.
This is my current approach:
def missing_number(array)
  sum = 0
  array.each do |element|
  sum += element
  end

  ((10000*10001)/2) - sum
end

Where I am getting tripped up is the output when I input an array such as this:
puts missing_number(*1..10000) #=> 0 

Why does this happen?
Thanks! 

A:

No need to sort the array.  An array of length N is supposed to have all but one of the numbers 1..(N+1) so the array length + 1 is the basis for figuring out what the grand_sum would be if all values were there.
def missing_number(array)
  grand_sum = (array.length + 1) * (array.length + 2) / 2
  grand_sum - array.inject(:+)
end

ADDENDUM
This method takes an array as an argument, not a range.  You can't use a range directly because there wouldn't be a missing value.  Before calling the method you need some mechanism for generating an array which meets the problem description.  Here's one possible solution:
PROBLEM_SIZE = 10_000
# Create an array corresponding to the range
test_array = (1..PROBLEM_SIZE).to_a
# Target a random value for deletion -- rand(N) generates values in
# the range 0..N-1, inclusive, so add 1 to shift the range to 1..N
target_value = rand(PROBLEM_SIZE) + 1
# Delete the value and print so we can check the algorithm
printf "Deleting %d from the array\n", test_array.delete(target_value)
# Randomize the order of remaining values, as per original problem description
test_array.shuffle!
# See what the missing_number() method identifies as the missing number                     
printf "Algorithm identified %d as the deleted value\n", \
       missing_number(test_array)

