|
| 1 | +# Power of two greater than a given Number |
| 2 | + |
| 3 | +We want to calculate the power of two which is greater than a given |
| 4 | +number |
| 5 | + |
| 6 | +**Naive solution** |
| 7 | + |
| 8 | +In this case, we need to use a loop. |
| 9 | + |
| 10 | +Let's set `number, power` which are two variables that represente respectively |
| 11 | +the number given to the function and the power of two obtained after each iteration. |
| 12 | +The variable `power` is initialize to 1 before the loop. |
| 13 | +As condition of our loop, we must check out if power is less than number. |
| 14 | +If it verified, we continue to run the loop and `power <- power*2` else we break it |
| 15 | +and return the value of the variable power. |
| 16 | + |
| 17 | +For exemple: consider number = 5 |
| 18 | + |
| 19 | +``` |
| 20 | +1. number = 5 and power = 1 (power < number) we continue |
| 21 | +2. number = 5 and power = 2 (power < number) we continue |
| 22 | +3. number = 5 and power = 4 (power < number) we continue |
| 23 | +4. number = 5 and power = 8 (power > number) we do not continue and we return 8 |
| 24 | +``` |
| 25 | +This method resolve the probleme but the complexity is great. |
| 26 | + |
| 27 | +**Optimal solution** |
| 28 | + |
| 29 | +The best solution for this problem is to use the logarithme function in basis 2. |
| 30 | + |
| 31 | +Note: log2(number) = ln(number) / ln(2) |
| 32 | + |
| 33 | +This expression return a real number and, if we consider the entire part of this |
| 34 | +and adding 1 of it we obtain a number. Assuming that this number is n, then if |
| 35 | +we calculate 2 power n we obtain the power of two which is directly greater than |
| 36 | +number. |
| 37 | + |
| 38 | +For exemple: consider number = 5 |
| 39 | + |
| 40 | +``` |
| 41 | + n = E(log2(number = 5)) + 1 |
| 42 | + n = E(ln(5) / ln(2)) + 1 |
| 43 | + n = E(2.3219...) + 1 |
| 44 | + n = 2 + 1 |
| 45 | + n = 3 |
| 46 | +
|
| 47 | + then 2 power n=3 equals 8 |
| 48 | +``` |
| 49 | + |
| 50 | +#reference |
| 51 | +"Logarithme binaire - Wikipédia" https://fr.m.wikipedia.org/wiki/Logarithme_binaire |
| 52 | + |
| 53 | + |
0 commit comments