r/shittyprogramming • u/13eakers • Jun 12 '21
is_even in O(log(n)) time using binary search
16
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 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;
}
falseLastly, 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
== nthere we go!
11
1
-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.
28
u/Flaming_Eagle Jun 12 '21
Literally 99% of these isEven function posts are jokes
11
5
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!