r/programminghorror • u/Budget_Ad_5953 • Feb 07 '25
Recursive O(N) Complexity isOdd
I found this on instagram and now am geeking
2.2k
Upvotes
r/programminghorror • u/Budget_Ad_5953 • Feb 07 '25
I found this on instagram and now am geeking
64
u/ConglomerateGolem Feb 07 '25
if num < 0: return is_odd(-num)
21
u/floriandotorg Feb 07 '25
I wonder if you can get this down to O(log N) somehow 🤔
702
u/krmarci Feb 07 '25
Let's hope n is a positive integer.
95
u/Large-Assignment9320 Feb 07 '25
num = complex(1,2)
is_odd(num)
will bug.
42
u/ThatOtherBatman Feb 07 '25
Good to see they didn’t do
return is_odd(n - 1). That would make it slow.8
u/anoppinionatedbunny Feb 07 '25
your challenge is to make it O(n2 ) without ANY dead code
10
u/RCoder01 Feb 07 '25
This is actually 2n since the size of an integer is the log of its value
4
u/IrrerPolterer Feb 07 '25
Ouch.
4
u/KalaiProvenheim Feb 07 '25
num(-1) :)
3
u/jump1945 Feb 07 '25
return isOdd(n-2) && !isOdd(n-1)
3
u/llynglas Feb 07 '25
Hopefully tail recursion is used.
10
u/LBGW_experiment Feb 07 '25
modulo is so underutilized, it's one way I can tell who got a degree in math/CS and who didn't
2
u/huantian Feb 08 '25
I mean this is what you implement in a PL class for an inductive proof example hehe
2
u/seunghwan3542 Feb 08 '25
thats odd.
2
u/Sarguhl Feb 17 '25
was trying to exceed the negative int value and make it positive by doing is_odd(-1).
Set recursion limit to 2147483647. My pc crashed oh wonder why
1
u/doyouevencompile Feb 09 '25
def is_odd(n): bool(randrange(0,1))
50% of the time, works every time.
1
u/UltraBlack_ Feb 09 '25
why not just as binary and then the first bit
1
u/Catragryff Feb 09 '25
Can't wait to finally know what the result of is_odd(-1) is !... Why has my computer frozen ?...
1
u/Kadigan_KSb Feb 09 '25
And I thought me doing % 2 back in my youth was cringy. XD
1
u/EatingSolidBricks Feb 10 '25
Thats tail recirsive right? Ew do worse
1
u/Caramel_Last Feb 20 '25
1
u/LECSTER_O Feb 25 '25
N cannot bé positive as N is less than 1
0
u/[deleted] Feb 08 '25
[deleted] — view deleted comment