I was solving a cipher problem with JavaScript and wanted to merge encoding and decoding functions.
In order to do that I needed a function that returns a number in a range in a cyclic way.
Knowing the properties of the modulo function, that returns the remainder of a division, by trial and error I reached this result:
- k(n,i,a):=mod(mod(n-i,-i+a+1)-i+a+1,-i+a+1)+i
Where 'n' is the number i want to put in the cycle, 'i' is the minimum in the range and 'a' the maximum.
The function in JS:
In the image I have the proof that it works at least for the range I need.
I would like to know if the function is correct, and if it is in its simpler form. It have to work only with integers.
Thank you for your time.
In order to do that I needed a function that returns a number in a range in a cyclic way.
Knowing the properties of the modulo function, that returns the remainder of a division, by trial and error I reached this result:
- k(n,i,a):=mod(mod(n-i,-i+a+1)-i+a+1,-i+a+1)+i
Where 'n' is the number i want to put in the cycle, 'i' is the minimum in the range and 'a' the maximum.
The function in JS:
JavaScript:
circularNumberInRangeBothWays(num, min, max) {
const diff = -min + max + 1
return ((num - min) % diff + diff) % diff + min
}
In the image I have the proof that it works at least for the range I need.
I would like to know if the function is correct, and if it is in its simpler form. It have to work only with integers.
Thank you for your time.