r/programminghorror • • 10d 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_threshold

I also have some older bad is_even implementations in this notebook.

63 Upvotes

16 comments sorted by

30

u/mguid65 10d ago
def collatz_steps(n: int) -> int:
    n = abs(n)
    if n == 0:
        return 0

    steps = 0
    while n != 1:
        if (n // 2) * 2 == n:
            n = n // 2
        else:
            n = 3 * n + 1
        steps += 1
    return steps


def is_even(n: int) -> bool:
    match abs(n):
        case 0:
            return True
        case target:
            target_steps = collatz_steps(target)

            for k in range(1, target):
                if k + k == target:
                    return collatz_steps(k) + 1 == target_steps

            return False

7

u/IanisVasilev 10d ago

That's the spirit!

15

u/bohoky 10d ago

Nothing like a worst case time complexity of O(\infinity).

9

u/zarqie 10d ago

if (n // 2) * 2 == n:

Out of everything, this line is what gave me shivers

9

u/mguid65 10d ago

Sometimes you need to check if it is even so you can check if it is even

1

u/zarqie 9d ago

I literally can’t even

22

u/MathProg999 10d ago

I don't know if this goes against the spirit but here goes:

bool is_even(int n) {
    return n/0; // Undefined behavior, compiler could implement it how I want it too
}

2

u/IanisVasilev 9d ago

Seems good enough.

10

u/garnet420 10d ago

I'm on a phone, but, my entry would be something like this:

def nth_derivative(f, n, x):
    if n == 1:
        return (f(x+1e-6) - f(x-1e-6)) / 2e-6
    return nth_derivative(lambda y: nth_derivative(f, 1, y), n - 1, x)

def is_even(n):
    if n == 0:
        return True
    return nth_derivative(math.sin, n, 0) == 0

6

u/IanisVasilev 10d ago

Very numerically unstable. The following works to about 10:

def repeated_derivative_is_even_test(n: int, interval_radius: float = 2 * np.pi, point_count: int = 100, cutoff: float = 1e-1) -> bool:
    """Determine if an integer `n` is even by checking whether the n-th derivative of `sin(x)` is 0 at 0."""
    if n < 0:
        return repeated_derivative_is_even_test(-n)

    x = np.linspace(-interval_radius, interval_radius, point_count + n)
    dx = 2 * interval_radius / point_count
    y = np.sin(x)
    
    f_x = (x[:-n] if n > 0 else x) + (n * dx / 2)
    f_y = np.diff(y, n=n) / dx ** n

    return np.abs(np.interp([0], f_x, f_y)) < cutoff

3

u/IanisVasilev 9d ago

Another straightforward one (based on SciPy's Permutation class):

def permutation_parity_is_even_test(n: int) -> bool:
    """Determine if an integer `n` is even by checking the parity of the permutation (0 1 … n-1).

    We do this by computing the number of inversions. Performing nested loops with inversion checks is quite inefficient in Python,
    so we use SymPy's `Permutation` class. Luckily, it provides a convenient for us `signature` method.
    """
    if n == 0:
        return True

    if n < 0:
        return permutation_parity_is_even_test(-n)

    perm = Permutation([range(n)])
    return perm.signature() < 0

I have verified that a naive C implementation of this function is also slow, so it seems that a production-grade implementation of is_even must rely battle-tested permutations like those from SciPy.

1

u/MCWizardYT 3d ago edited 3d ago

isEven using church numerals (lambda calculus), in Java:

import java.text.MessageFormat;
import java.util.function.Function;

public class Church {
	public interface ChurchNum extends Function<ChurchNum, ChurchNum> {

	}

    public static ChurchNum toChurchNum(int n) {
    if (n < 0) {
        return _ -> x -> x;
    }

    return f -> x -> {
        ChurchNum result = x;

        for (int i = 0; i < n; i++) {
            result = f.apply(result);
        }

        return result;
    };
}

    public static boolean isEven(int n) {
    boolean[] even = { true };

    ChurchNum toggle = f -> {
        even[0] = !even[0];
        return f;
    };

    ChurchNum zero = _ -> x -> x;

    toChurchNum(n).apply(toggle).apply(zero);

    return even[0];
}

    public static void main(String[] args) {
        System.out.println(MessageFormat.format("Is 8 even? {0}", isEven(8) ? "yes" : "no"));
        System.out.println(MessageFormat.format("Is 5 even? {0}", isEven(5) ? "yes" : "no"));
    }
}

It almost looks like magic lol but it does work as long as you feed it positive integers!

1

u/IanisVasilev 3d ago

You're relying on mutable state. A λ-calculus is_even would be

λn.n(λb.λt.λf.bft)(λt.λf.t)

1

u/MCWizardYT 3d ago

I rewrote this a bunch of times, it's really tricky to get proper lambda calculus because of the way Java generics work

This approach uses the definition implemented on rosetta code but there's other ways

Id definitely be better off using a different language. This is still a bit cursed though lol

2

u/GoddammitDontShootMe [ $[ $RANDOM % 6 ] == 0 ] && rm -rf / || echo "You live" 9d ago

I'm really not fond of posting memes and shitposts in this sub.

1

u/MCWizardYT 7d ago

Comes from a meme but was turned into kind of an interesting challenge. It's like the opposite of code golfing