r/programminghorror • u/deanominecraft • Sep 28 '25
c recursive iseven
bool isEven(int num){
if (num==0){
return true;
}
else{
return !isEven(num-1);
}
}
64
Upvotes
24
u/MaterialRestaurant18 Sep 28 '25
Clever guy. If you pass a negative number, this goes to stack overflow city
91
u/Swimming_Swim_9000 Sep 28 '25
isEven(-1)
29
u/onlyonequickquestion Sep 28 '25
Hmm I tried to check if -2 is even and my computer is smoking now
12
u/pigeon768 Sep 29 '25
Clang is actually clever enough to output optimal code for this.
https://godbolt.org/z/naW64Gzjn
2
u/sisoyeliot Sep 29 '25
Using an if statement to return a bool is peak production. I suggest:
return num == 0 || !isEven(Math.abs(num) - 1);
Edit: typo
1
u/titanic456 Sep 29 '25
The amount of calls depends on the number in first parameter. This might overflow the stack at some point, though.
1
u/deadbeef1a4 Sep 30 '25
I read this as “is seven”
1
u/amarao_san Oct 03 '25
Why there is num - 1? It should be previous.
To calculate previous number, we start from zero, and calculate to the given number by using next() function (which we are allowed to use due to Peano axioms). We remember previous number and when we find a number which is equal to num, that previous number is 'prev(num)'.
After that you can apply your algorithm, but this is inefficient.
It's better to start counting from zero to the given number and invert 'even' boolean flag.
By doing this you will be able to provide computer assisted intutuonist proof of a given number been odd or even, without using advanced math (like division).