Hi, was wondering if there's a more mathematical approach to calculating a sequence of numbers where each number multiplies itself by 2. so starting with the number 5, and running 6 levels you would end up with

5, 10, 20, 40, 80, 160

I've got this and it works, but wondering if there's a more efficient way of doing it?

In code, you can do this using the bitshift operator as well instead of using pow or something, courtesy of binary:

n = 5 << (level - 1);

Watch out for overflow though. Of course, if later on you want to have partial levels, e.g. level = 2.5 somewhere between level 2 and level 3, then just using pow is the better solution, since you're using floats anyway.

Edited by Bacterius, 12 August 2014 - 06:06 PM.

“If I understand the standard right it is legal and safe to do this but the resulting value could be anything.”

Say I wanted to get the inverse of that function. Given these numbers:

5, 10, 20, 40, 80, 160

how could I produce:

1, 2, 3, 4, 5, 6

It would be:

level = log2(n / 5) + 1

Where log2 is the base-two logarithm. (again, if using bitshifts and integers, log2 can be implemented as the "highest bit set to one" instruction, which has no built-in keyword but may have an intrinsic available on your compiler - but at this point, using your math library's log2 is probably easier).

So e.g. for n = 80, we take n / 5 = 16, and log2(16) = 4 which gives us level = 5, as expected.

“If I understand the standard right it is legal and safe to do this but the resulting value could be anything.”

Your sequence increases by multiples of the repeating sequence [5, 2, 3, 2], so for each multiple of 4 indices, the sequence increases by a factor 60. The remainder of a multiple by 4 can easily be applied afterwards.

Two hints:

(index-1)/4 gives you the number of times to multiply by 60.

(index-1)%4 gives you the number of factors to multiply as a fraction of 60; for no remainder you multiply by 1 since all factors are covered by a whole number of 60's, for one remainder you multiply by 1*5=5, for two remainders you multiply by 1*5*2=10, and so on for the last factor which I leave up to you to understand.