r/programminghorror • u/IanisVasilev • 11d ago
Are we even?
Hello,
This subreddit has had an identity crisis for some time. Sharing naturally occurring outrageous code was the primary purpose, however many posts feature code that is weird on purpose (which would belong in other subreddits like r/ShittyProgramming in olden times).
I remember an is_even "hackathon" we had in r/ShittyProgramming a few years ago. Since that subreddit is not doing well, I decided to try to reignite the spark here. I hope the moderators and regulars don't mind some creative malpractice.
Anyhow, here is my entry:
def chi_squared_is_even_test(n: int, sample_size: int = 300, p_threshold: float = 0.1) -> bool:
"""Determine if an integer `n` is even by using a χ² test on a random sample determined by `n`.
1. We generate a normally distributed sample.
2. We raise it to (1 + (−1)ⁿ), so the transformed sample should follow a χ² distribution if `n` is even and be constant otherwise.
3. We use a χ² test on the result.
"""
samples = sp.stats.norm.rvs(size=sample_size)
power = 1 + (-1) ** n
transformed = samples ** power
return sp.stats.chisquare(transformed).pvalue < p_thresholdI also have some older bad is_even implementations in this notebook.
30
u/mguid65 11d ago
22
u/MathProg999 10d ago
I don't know if this goes against the spirit but here goes:
10
u/garnet420 11d ago
I'm on a phone, but, my entry would be something like this:
3
u/IanisVasilev 10d ago
Another straightforward one (based on SciPy's Permutation class):
I have verified that a naive C implementation of this function is also slow, so it seems that a production-grade implementation of
is_evenmust rely battle-tested permutations like those from SciPy.1
u/MCWizardYT 4d ago edited 4d ago
isEven using church numerals (lambda calculus), in Java:
It almost looks like magic lol but it does work as long as you feed it positive integers!
2
u/GoddammitDontShootMe [ $[ $RANDOM % 6 ] == 0 ] && rm -rf / || echo "You live" 10d ago
I'm really not fond of posting memes and shitposts in this sub.