Is power of 3?

 Today's AlgoDaily problem is to determine whether a number is a power of 3. 

 One solution is to keep dividing the number by 3 while the dividend is greater than one. You record check the last element in this sequence of divisions. If this element is a fraction, you know there was a remainder and the number is not a power of 3. If the last number in the sequence of divisions is 1, you know the number is a perfect power of three. 

 A different way to look at the solution that has the same complexity is to think of these division operations as representing the number in a 3-ary number system. Check out this video on number systems by 3Blue1Brown, it's amazing https://www.youtube.com/watch?v=2SUvWfNJSsM You keep dividing by 3 and the remainder is what goes into the position of the 3**i'th digit (you populate the 3-ary representation in reverse order). A number that is a power of 3 in this representation has 1 in the leading digit and all the rest are zeros, because there are no remainders in the subsequent steps. So you can make a condition that if your remainder when you divide by 3 is ever anything else but zero, you return False. This is the more elegant way!

Number systems are about making number vesicles, tiny units that contain the remainders when you divide your total quantity into pieces of 2 (binary) or 3 (ternary) or 10 (decimal) etc... The 3Blue1Brown video illustrates it so beautifully!


My solution:  https://github.com/mariakesa/Algorithms/blob/master/AlgoDaily/AlgorithmsPractice.ipynb

Kommentaarid