Isn’t this actually O(1)? The algorithm always does a binary search on [0…u32::MAX] regardless of n. So it’s upper bound by the constantlog(u32::MAX), meaning it should be O(1). That’s the best kind of O!
Yes, I thought about this pretty much immediately after I made the post. But fortunately this is shitty programming so any mistakes in the post we can just reclaim as features, Bethesda style.
But don't worry, there's some easy ways to fix it.
First off, you can write the if chain as a match
match (m * 2).cmp(&n){
Ordering::Less => {
m += step;
}
Ordering::Greater => {
m -= step;
}
Ordering::Equal => {},
}
(you still need the if m * 2 == n).
Also, using a while loop is bad style! You should be using iterators for that!
for step in (0..32_u32).rev().map(|x| 1<<x) {
// code here
}
You can also pull the early return out of the loop! That lets us do this transformation:
let m = (0..32_u32)
.rev()
.map(|x| 1 << x)
.fold(u32::MAX / 2, |m, step| {
use std::cmp::Ordering;
match (m * 2).cmp(&n) {
Ordering::Less => m + step,
Ordering::Greater => m - step,
Ordering::Equal => m,
}
});
if m * 2 == n {
return true;
}
false
Lastly, we can trivially inline the temporary variables and
(0..32_u32)
.rev()
.map(|x| 1 << x)
.fold(u32::MAX / 2, |m, step| {
use std::cmp::Ordering;
match (m * 2).cmp(&n) {
Ordering::Less => m + step,
Ordering::Greater => m - step,
Ordering::Equal => m,
}
})
* 2
== n
9
u/moeghoeg Jun 12 '21 edited Jun 12 '21
Isn’t this actually
O(1)? The algorithm always does a binary search on[0…u32::MAX]regardless ofn. So it’s upper bound by the constantlog(u32::MAX), meaning it should beO(1). That’s the best kind ofO!16
u/[deleted] Jun 12 '21
This is actually bad code!
But don't worry, there's some easy ways to fix it.
First off, you can write the
ifchain as amatch(you still need the
if m * 2 == n).Also, using a
whileloop is bad style! You should be using iterators for that!You can also pull the early return out of the loop! That lets us do this transformation:
Lastly, we can trivially inline the temporary variables and
there we go!
11
u/malduvias Jun 12 '21
Yep 👍 This is shit.
1
u/DramaDimitar Aug 11 '21
What language is this?
-10
u/TheRedmanCometh Jun 12 '21 edited Jun 12 '21
That's gotta be a joke. No one smart enough to do this is dumb enough to do this.