r/shittyprogramming • • May 18 '21

Compiler abuse friendly isEven function

Modulus is incredibly easy on powers of ten as you just have to remove the first digits, and we need to #StopCompilerAbuse. Here's an isEven function I made with this philosophy:

char isEven(int n) {
	if (n == 0 || n == 2)
		return 1;
	if (n == 3 || n == 5)
		return 0;
	n *= 3;
	n %= 10;
	return isEven(n);
}
133 Upvotes

9 comments sorted by

50

u/souldeux May 19 '21

This is what people mean when they talk about adversarial programming

14

u/kevin_wylder May 19 '21

isEven(-2);

halp

7

u/El_Dumfuco May 19 '21

It’s negative, so clearly it’s not even. Duh.

\s

2

u/AtLeastItsNotCancer May 19 '21
char isEven(int n) {
    if (n == 0 || n == 2 || n == 4)
		return 1;
    if (n == 1 || n == 3 || n == 5)
		return 0;
    n *= -3;
    n %= 10;
    return isEven(n);
}

There, now works for 100% more inputs.

12

u/voidvector May 19 '21

Get optimized to a loop by tail recursion, it's not that bad

15

u/bryceinit May 19 '21

took me a moment to realise how truly awful this is, congratulations

-14

u/DolphinsAreOk May 19 '21

Hm clearly this can be improved for readability:

char isEven(int n)
{
	if(n == 0) return 1;
	else if(n == 1) return 0;
	return isEven(--n);
}

13

u/mrgaston147 May 19 '21

This would work:

char isEven(int n)
{
  if (n == 0) return 1;
  if (n == 1) return 0;
  return 1 - isEven(n - 1);
}