2

I need to find one missing number, from a sequence of numbers

such as

4 8 12 16 __ 24.

I need to find the missing number. How would I do that programmatically?

the numbers and the missing placement are not static, so they should be able to change.

Hope it is possible.

9
  • 2
    Sounds like an interesting problem. What have you tried? Commented Jul 12, 2013 at 0:41
  • It is impossible because there are infinite number of ways you can build your logic. What you can do is to limit it to only several methods of building sequences which will make it a trivial loop-through.. Commented Jul 12, 2013 at 0:43
  • I'd also say this is a math.stackoverflow question because there is no particular programming aspect here. Commented Jul 12, 2013 at 0:45
  • Isn't it just difference / 2? Commented Jul 12, 2013 at 0:48
  • @Simon Whitehead: I think the OP wants the program to find the missing number of an arbitrary series of numbers, (if I understood correctly, that is). Commented Jul 12, 2013 at 0:51

2 Answers 2

2

You could use some silly linq like this silly example :)

var numbers = new List<int>{4, 8, 12, 16, 24, 28, 36};
int first = numbers.First();
int last = numbers.Last();

var missing = Enumerable.Range(first, last).Where(n => n % first == 0).Except(numbers);


Returns:
20
32

-Bracing self for downvotes-

Sign up to request clarification or add additional context in comments.

2 Comments

this assumes that you'll that your first element is equal to the difference between all the elements in the list.
In an interview (which is where this problem is usually seen), you would probably be told to make a more general solution, i.e. not using Linq. Also it would need to work with negative and positive values.
1

If you know that it is always an Arithmetic Progression, you can use the formula:

an = a1 + (n - 1) * d

being a1 the first element, d the difference between 2 elements and n the position to calculate, in your case:

an = 4 + (5 - 1) * 4 = 20

Check this: https://en.wikipedia.org/wiki/Arithmetic_progression

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.