One way to be sneaky about solving this problem comes from realizing what the problem is asking for when it says to "divide by 2 until we reach an odd number." If you think about the binary representation of an integer, there's only one way for it to be odd - that is, for its lowest/least-significant bit to be set to 1. Also recalling that dividing by two is equivalent to a single bitshift to the right, we can find a neat trick.
With 12 as an example, we can see that in binary it is 1100, so it would take two bitshifts right for it to be odd - that is, to turn it into 11 (3). So we don't need to actually divide 12 until we get 3, but simply count the number of trailing zeroes in 12 and use that as its strength - which would be 2, in this case. From there, we just need to keep track of the largest-strength-with-smallest-number combo and we'll be fine. With all that said, here's that strategy implemented in Python:
#!/usr/bin/env python3
deftrailing_zeroes(num):num_trailing=0whilenum&1==0:# loop/bitshift right until we find a nonzero bit
num_trailing+=1num=num>>1returnnum_trailingdeffind_strongest(start,stop):"""Return the strongest number in a closed interval as per dev.to challenge #152
"""max_strength=0best_num=0# add 1 to halt the loop at the value of stop, not stop - 1
foriinrange(start,stop+1):ifi%2==1:# don't bother with odd numbers
continue# the strength given in the spec can be expressed
# as the number of trailing zeroes in the number
strength=trailing_zeroes(i)ifstrength>max_strength:max_strength=strengthbest_num=ielifstrength==max_strength:# as per the spec, choose the lower number
best_num=min(best_num,i)returnbest_numif__name__=="__main__":print(find_strongest(1,2))print(find_strongest(5,10))print(find_strongest(48,56))print(find_strongest(129,193))
edit/take #2: I tried to think about a way to optimize the trailing zero calculation for a while, but couldn't come up with anything; so I gave up and decided to search around a little bit to find if anyone came up with an O(1) method to calculate the trailing-zero problem instead of the naive linear solution I posted. Turns out someone did, and the link can probably explain better than I. The result of integrating that solution with the code I posted earlier is below:
#!/usr/bin/env python3
# the below function is adapted from https://graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightModLookup
deftrailing_zeroes_fast(num):lookup=[32,0,1,26,2,23,27,0,3,16,24,30,28,11,0,13,4,7,17,0,25,22,31,15,29,10,12,6,0,21,14,9,5,20,8,19,18]num_trailing=lookup[(-num&num)%37]returnnum_trailingdeffind_strongest(start,stop):"""Return the strongest number in a closed interval as per dev.to challenge #152
"""max_strength=0best_num=0# add 1 to halt the loop at the value of stop, not stop - 1
foriinrange(start,stop+1):ifi%2==1:# don't bother with odd numbers
continue# the strength given in the spec can be expressed
# as the number of trailing zeroes in the number
strength=trailing_zeroes_fast(i)ifstrength>max_strength:max_strength=strengthbest_num=ielifstrength==max_strength:# as per the spec, choose the lower number
best_num=min(best_num,i)returnbest_numif__name__=="__main__":print(find_strongest(1,2))print(find_strongest(5,10))print(find_strongest(48,56))print(find_strongest(129,193))
As a sidenote, an alternative method to count trailing zeroes to is to use the base 2 log of (-num & num), i.e, math.log2(num & -num) - in essence, this is asking how many bitshifts left starting from 1 are needed to hit the first set bit of num - but while it's clearly shorter and definitely more understandable, I don't believe this is faster than the lookup table route.
The optimization of using bit operations to find the "strength" of a number is a low hanging fruit, but the relationship between the number's strength and its binary representation can be taken much farther than that - to the point of solving this in logarithmic(!) time:
fnstrongest_number(min:usize,max:usize)->usize{assert!(min<=max);ifmin==max{// Otherwise the second `while` loop will not endreturnmin;}letmutprefix_mask=!0usize;while0!=(prefix_mask&max){prefix_mask<<=1;}while(prefix_mask&max)==(prefix_mask&min){prefix_mask|=prefix_mask>>1;}if(prefix_mask&min)==min{min}else{prefix_mask&max}}fnmain(){assert_eq!(strongest_number(1,2),2);assert_eq!(strongest_number(5,10),8);assert_eq!(strongest_number(48,56),48);assert_eq!(strongest_number(129,193),192);}
Explanation:
You can compare two numbers, padded to the same length, by finding their longest common prefix and then looking at the highest digit that's different. This work in any base, but farther ahead we'll use some properties unique to binary so let's stick with that.
For example, if we take 129 and 193 and convert them to binary:
129: 0000000010000001
193: 0000000011000001
We can see that both start with 000000001, and then 129 has 0000001 while 193 has 1000001. So the highest nonshared digit is 0 for 129 and 1 for 193 - which is why 193 is higher (yup - that's the direction the causation works here. Though this is math, so one can twist it to be the other way around...)
Lemma: Any number between the lower and higher bounds will share that same prefix with them.
Proof: If it doesn't, then at least one digit is different. Take the most significant digit where the number is different than the shared prefix. If it's 0 for the number and 1 for the prefix - this means the number is lower than the lower bound. If it's 1 for the number and 0 for the prefix - this means the number is higher than the higher bound.
So, the strongest number, being in the range, must also have that prefix. The strongest number with that prefix is just the prefix with only zeroes after it (remember - the number of digits is fixed!). That's also the lowest number in that range, so if it's equal to the lower bound - that's the strongest number in the range. Otherwise - the next strongest number is the prefix, a single one after it, and after that only zeroes. This number is guaranteed to not be higher than the higher bound, because they share the original common prefix plus a single one after it - and that number is the lowest in that prefix, since after that it's all zeroes.
The g method takes a number, converts it to binary, and return the number of trailing zeroes. Then, the f method loops through the input interval in order to return the maximum power
Time flies while you're having fun, but then one day your bio says something about being a 30+ year veteran in software engineering. Still, I've not seen it all, let alone done it all (yet).
Time flies while you're having fun, but then one day your bio says something about being a 30+ year veteran in software engineering. Still, I've not seen it all, let alone done it all (yet).
There is no built in "MaxBy" in the C#, so here I replaced it with an Aggregate. (The TrailingZeroCount method will use intrinsics (e.g. a CPU instruction) if its available, so I'm not worried about calling it repeatedly for the accumulator.)
proc even(i:int):bool{.inline.}=imod2==0proc numStrength(i:int):int=## Calculate the strength of a number.#### A number's strength is determined by the number of times## it can divided in half until it reaches an odd number.vari=iwhilei.even:i=idiv2inc(result)proc strongestNum(n,m:int):int=## Given the closed interval [n, m], calculate the strongest number.vartopStrength=0foriinn..m:letstrength=numStrength(i)ifstrength>topStrength:topStrength=strengthresult=iassertstrongestNum(1,2)==2assertstrongestNum(5,10)==8assertstrongestNum(48,56)==48assertstrongestNum(129,193==192
There's definitely room to improve this, but I'm just starting to look into Nim's standard library, and I don't know all that's available to me yet.
One way to be sneaky about solving this problem comes from realizing what the problem is asking for when it says to "divide by 2 until we reach an odd number." If you think about the binary representation of an integer, there's only one way for it to be odd - that is, for its lowest/least-significant bit to be set to 1. Also recalling that dividing by two is equivalent to a single bitshift to the right, we can find a neat trick.
With 12 as an example, we can see that in binary it is
1100, so it would take two bitshifts right for it to be odd - that is, to turn it into11(3). So we don't need to actually divide 12 until we get 3, but simply count the number of trailing zeroes in 12 and use that as its strength - which would be 2, in this case. From there, we just need to keep track of the largest-strength-with-smallest-number combo and we'll be fine. With all that said, here's that strategy implemented in Python:edit/take #2: I tried to think about a way to optimize the trailing zero calculation for a while, but couldn't come up with anything; so I gave up and decided to search around a little bit to find if anyone came up with an O(1) method to calculate the trailing-zero problem instead of the naive linear solution I posted. Turns out someone did, and the link can probably explain better than I. The result of integrating that solution with the code I posted earlier is below:
As a sidenote, an alternative method to count trailing zeroes to is to use the base 2 log of
(-num & num), i.e,math.log2(num & -num)- in essence, this is asking how many bitshifts left starting from 1 are needed to hit the first set bit ofnum- but while it's clearly shorter and definitely more understandable, I don't believe this is faster than the lookup table route.The optimization of using bit operations to find the "strength" of a number is a low hanging fruit, but the relationship between the number's strength and its binary representation can be taken much farther than that - to the point of solving this in logarithmic(!) time:
Explanation:
You can compare two numbers, padded to the same length, by finding their longest common prefix and then looking at the highest digit that's different. This work in any base, but farther ahead we'll use some properties unique to binary so let's stick with that.
For example, if we take 129 and 193 and convert them to binary:
We can see that both start with
000000001, and then 129 has0000001while 193 has1000001. So the highest nonshared digit is0for 129 and1for 193 - which is why 193 is higher (yup - that's the direction the causation works here. Though this is math, so one can twist it to be the other way around...)Lemma: Any number between the lower and higher bounds will share that same prefix with them.
Proof: If it doesn't, then at least one digit is different. Take the most significant digit where the number is different than the shared prefix. If it's
0for the number and1for the prefix - this means the number is lower than the lower bound. If it's1for the number and0for the prefix - this means the number is higher than the higher bound.So, the strongest number, being in the range, must also have that prefix. The strongest number with that prefix is just the prefix with only zeroes after it (remember - the number of digits is fixed!). That's also the lowest number in that range, so if it's equal to the lower bound - that's the strongest number in the range. Otherwise - the next strongest number is the prefix, a single one after it, and after that only zeroes. This number is guaranteed to not be higher than the higher bound, because they share the original common prefix plus a single one after it - and that number is the lowest in that prefix, since after that it's all zeroes.
That is just so clean, well thought and well explained! Congrats!
Some JS oneliners!
The
gmethod takes a number, converts it to binary, and return the number of trailing zeroes. Then, thefmethod loops through the input interval in order to return the maximum powerDon't write functions that already exist...
(F#)
Available since .NET Core 3.0 ... nice touch! Also in F# the Sequence generation is SO MUCH easier.
In C# you'd be better off with a simple for-loop.
Well, my F# solution translated to C# would be something like this;
There is no built in "MaxBy" in the C#, so here I replaced it with an Aggregate. (The TrailingZeroCount method will use intrinsics (e.g. a CPU instruction) if its available, so I'm not worried about calling it repeatedly for the accumulator.)
Hello guys, this is my first time here, and this is my recursive approach:
EDIT without times:
Inefficient Python w/ tail recursion:
Not the most efficient answer, but it is!
CodePen
Haskell
Try it.
Probably not a very efficient way to do it, but it works:
Did it long hand in js. Great puzzle!
Here's a Nim submission!
There's definitely room to improve this, but I'm just starting to look into Nim's standard library, and I don't know all that's available to me yet.
Ruby
In Go.