Thursday, September 29, 2016

Circle of Numbers (CodeFIght)

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;
}
 

2 comments:

  1. Replies
    1. First 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