Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

If I have: { 0, 1, 2, 3, 4, 5, 6 }

How can I make a function that will return the number of steps to a target element, in one direction?

To clarify, let the target be 2... Say that x = 5, and I want my function to move backwards to find 2, and return -3.. And say that x = 0, it needs to return -5.

That's where I am confused.. Normally with my understanding of algebra, something like:

5 - x = 2 ==> x = 3

That satisfies my first scenario (if I negate it).. but, the second:

0 - x = 2 ==> x = -2 ... not what I want..

Is there some simple way to do this that I am not seeing?

share|cite|improve this question
Is the answer you're looking for just to do the arithmetic mod the length of the list? So in the example you gave, $-2 \equiv 5 (\mod 7)$, so if the number is negative, you just return seven (the length in the general case) plus the number. – Luke Mathieson Sep 12 '12 at 9:53

You can add n to x, subtract the target from x, and then take the mod n of the result where n is the number of elements. For example, if you have x=5, and your target is 2, then do 7+x=7+5=12. 12-2 = 10. 10 mod 7 = 3. And then you make the 3 negative since you are going backwards. If x=0, then do 0+7=7. 7-2 = 5. 5 mod 7 = 5, and make that negative again.

share|cite|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.