Consider integer numbers from 0 to n - 1 written down along the circle in such a way that the distance between any two neighbouring numbers is equal (note that 0 and n - 1 are neighbouring, too).
Given n and firstNumber, find the number which is written in the radially opposite position tofirstNumber.
Example
For n = 10 and firstNumber = 2, the output should be
circleOfNumbers(n, firstNumber) = 7.
Change Snippet Background Color
int circleOfNumbers(int n, int firstNumber) {
return (firstNumber+(n/2)) % n;
}
Can you explain the math?
ReplyDeleteFirst off, to get to other side, first off you'd want to divide n by 2, then offset it by firstNumber. To account for the rotation, you basically want to find the remainder after dividing it because it's always goin to a value between 0 and n, which is where modulus comes in.
Delete