460
you are viewing a single comment's thread
view the rest of the comments
[-] Aedis@lemmy.world 33 points 1 week ago

I'm partial to a recursive solution. Lol

def is_even(number):
    if number < 0 or (number%1) > 0:
        raise ValueError("This impl requires positive integers only") 
    if number < 2:
        return number
    return is_even(number - 2)
[-] tetris11@lemmy.ml 18 points 1 week ago* (last edited 1 week ago)

I prefer good ole regex test of a binary num

function isEven(number){
   binary=$(echo "obase=2; $number" | bc)
   if [ "${binary:-1}" = "1" ]; then
         return 255
   fi
   return 0
}
[-] balsoft@lemmy.ml 8 points 1 week ago* (last edited 1 week ago)

Amateur! I can read and understand that almost right away. Now I present a better solution:

even() ((($1+1)&1))

~~(I mean, it's funny cause it's unreadable, but I suspect this is also one of the most efficient bash implementations possible)~~

(Actually the obvious one is a slight bit faster. But this impl for odd is the fastest one as far as I can tell odd() (($1&1)))

[-] Aedis@lemmy.world 2 points 1 week ago

I'm waiting for a code golf style solution now.

[-] balsoft@lemmy.ml 2 points 1 week ago

I don't think there's much to codegolf. The "obvious" solution (even() (($1%2))) is both shorter and faster. Don't think it can be optimized much more.

load more comments (5 replies)
load more comments (9 replies)
load more comments (9 replies)
this post was submitted on 15 Jul 2025
460 points (94.7% liked)

Programmer Humor

37361 readers
102 users here now

Post funny things about programming here! (Or just rant about your favourite programming language.)

Rules:

founded 6 years ago
MODERATORS