Reposted from Stack Overflow - I think this is a more appropriate place to ask the question.
I have an algorithm that for an integer x and a starting integer i such that 1 < i < x the next value of i is computed by i = floor(x / i) + (x mod i). This continues until we reach an i that we've already seen.
In JavaScript (though this question is language agnostic):
function f(x, i) {
var map = {};
while(!map[i]) {
map[i] = true;
i = Math.floor(x / i) + (x % i); // ~~(x / i) is a faster way of flooring
}
return i;
}
I can prove that we will eventually reach an i we've already seen, but I'm wondering:
- Is there is a more efficient way of computing the next
i? - (More importantly) Is there is a way to compute the nth
iwithout running through the loopntimes?
Just to clarify - I know there are faster ways than using JS hash maps for that check, and that flooring can be replaced by integer division in other languages. I have made both of those optimizations, but I left them out to try to make the code easier to understand.