The less readable one is faster, though I’d be surprised if the compiler doesn’t generate the same code for both of those options with optimizations enabled.
I like the regex one as another unnecessarily complicated way of doing it. It also involves a string conversion.
The way that was being hinted at before my reply was a large series of if statements: is it 2? 4? 6? 8? And so on. It’s plausible in that I could see a beginner programmer using that method. And honestly, knowing how people can get pigeon holed into looking at a problem from some weird angle but still having the determination to figure it out, most solutions are plausible. Often when they get pointed in a better direction, it’s not so much a case of them learning something new as it is a facepalm kinda moment where they feel embarrassed at not seeing that. I’ve done it myself many times lol.
It’s always funny seeing someone use the wrong tool for the job but still getting the job done, even when it’s me.
Godbolt to the rescue! So gcc 13.2 certainly does produce the same code, though a lot of other versions and compilers do it slightly differently. Surprisingly, clang doesn’t optimise this and uses idiv for the modulo version.
The less readable one is faster, though I’d be surprised if the compiler doesn’t generate the same code for both of those options with optimizations enabled.
I like the regex one as another unnecessarily complicated way of doing it. It also involves a string conversion.
The way that was being hinted at before my reply was a large series of if statements: is it 2? 4? 6? 8? And so on. It’s plausible in that I could see a beginner programmer using that method. And honestly, knowing how people can get pigeon holed into looking at a problem from some weird angle but still having the determination to figure it out, most solutions are plausible. Often when they get pointed in a better direction, it’s not so much a case of them learning something new as it is a facepalm kinda moment where they feel embarrassed at not seeing that. I’ve done it myself many times lol.
It’s always funny seeing someone use the wrong tool for the job but still getting the job done, even when it’s me.
Godbolt to the rescue! So gcc 13.2 certainly does produce the same code, though a lot of other versions and compilers do it slightly differently. Surprisingly, clang doesn’t optimise this and uses
idiv
for the modulo version.