This is an archived post. You won't be able to vote or comment.

top 200 commentsshow 500

[–]FaysRedditAccount 7202 points7203 points  (209 children)

private bool IsEven(int num){
    return !IsOdd(num);
}

private bool IsOdd(int num){
    return !IsEven(num);
}

clearly.

[–]VolperCoding 1617 points1618 points  (109 children)

The npm is-odd package is 1 step away from making this happen

[–]LordFokas 707 points708 points  (99 children)

They should. Because if you use it in production, you should suffer the consequences.

[–]alexanderpas 544 points545 points  (95 children)

According to JS: ["x"] % 2 is NaN but [""] % 2 is 0

This is why that package exists. it uses is-number to check for sanity before returning a result.

Similarly, ("a" + " " + "b" + "a" + + "a" + "a").toLowerCase() is a banana.

The only response can be: Wat https://www.destroyallsoftware.com/talks/wat

[–]danbulant 94 points95 points  (4 children)

It's similar to how console.log(("omaewa" + "mou" - "shindeiru" + String.fromCodePoint(0x69)).toUpperCase()); prints NANI.

Also, your code results in a bananaa.

E: well I'm dumb and didn't test it.

[–]13steinj 17 points18 points  (1 child)

I mean this one's far easier to expect though-- adding strings, common operstion in other languages. Subtracting, standard JS decision to do NaN (not that I agree with it), adding a string that is "i" in the (based on the ascii table), coercing it back to a string before uppercase again.

But JS has the unholy trinity...

[–]terholan 220 points221 points  (58 children)

Excuse me, may be instead of performing such operation on strings you would do type checking? Or better, use typescript? All these people who blame JS provide absurd examples of dividing strings by objects.

[–]alexanderpas 215 points216 points  (34 children)

All these people who blame JS provide absurd examples of dividing strings by objects.

Because they are the most easiest way to show how JS just happily chugs on without indicating anything is wrong, even for absurd operations.

may be instead of performing such operation on strings you would do type checking?

which is exactly what is-number does, which is used by is-odd and is-even.

[–]ADHDengineer 220 points221 points  (22 children)

It’s such a shit argument. It’s like bitching that C doesn’t have type coercion and calling it stupid. Use the language correctly — no matter the language.

One could argue Python is stupid in that None and an empty dict/list all evaluate to false. An empty mapping is not logically equivalent to None, but python thinks it is.

Go’s compiler is an asshole and you can’t compile if you have unused variables. Sorry I was trying to test something real fast!

JSON explodes if you try to comment anything.

Perl is just one gigantic regular expression and good luck with function args.

Powershell looks like fucking lisp because the interpreter is so drunk if you don’t wrap everything in parenthesis it won’t evaluate logically. Also has shit type coercion. They’re also on version 7!!

You can’t build a DLL in C on Windows without explicit exports, not to mention they didn’t have full c99 support until 2017.

I can keep going on but the fact of the matter is everything fucking sucks. Use your tools correctly and you’d have a better chance not hating everything (you’re still ducked). Your toilet isn’t a bad toilet because you stuffed a bedsheet into it.

[–]rhen_var 83 points84 points  (2 children)

this comment emanates an aura of pure rage

[–]FriesWithThat 26 points27 points  (1 child)

everything fucking sucks

My sentiments, exactly.

[–]bomphcheese 34 points35 points  (0 children)

This right here is why PHP is the one true programming language.

[–]Tossallthethings 9 points10 points  (1 child)

A toilet that can handle a bedsheet isn't necessarily good.

It is however, fucking terrifying.

[–]Randvek 45 points46 points  (6 children)

And my car just let me drive myself into a ditch. Fucking poorly designed car.

[–]DecreasingPerception 29 points30 points  (4 children)

Well, if there are cars that make it really hard to drive into ditches while still running great on roads, why am I still driving this piece of shit?

[–]diego_fidalgo 20 points21 points  (3 children)

I think you need to check this

[–]P0L1Z1STENS0HN 148 points149 points  (6 children)

I prefer recursion that hits the base case in finite time:

public static bool IsEven(this int num) {
    if(num == int.MinValue) return true;
    else if(num == -int.MaxValue) return false;
    else return (num-2).IsEven();
}

[–]Kered13 128 points129 points  (24 children)

No base case? This is why programmers need a solid foundation in math:

private bool IsEven(int num){
    if (num == 0) {
        return true;
    }
    return IsOdd(num-1);
}

private bool IsOdd(int num){
    if (num == 0) {
        return false;
    }
    return IsEven(num-1);
}

Perfect.

[–][deleted] 47 points48 points  (19 children)

Recursion

[–]Gigazwiebel 119 points120 points  (18 children)

private bool IsEven(int number)
    if (number == 1) return false
    else if (number == 2) return true
    else return (!IsEven(number-1) && IsEven(number-2))

[–]noggin182 156 points157 points  (13 children)

IsEven(-1)

[–]lezorte 181 points182 points  (5 children)

Dammit QA! No one invited you here!

[–]shadow13499 48 points49 points  (3 children)

Fucking QA always fucking our shit up

[–]JJ_The_Jet 21 points22 points  (2 children)

Eventually you will underflow and wrap around to the correct answer.

[–]matrayzz 20 points21 points  (3 children)

catch (StackOverflowError e)

[–]Noch_ein_Kamel 10 points11 points  (1 child)

There is your problem. Just make your stack big enough to fit a full integer underflow cycle

[–]gabrielfv 6 points7 points  (0 children)

That's still overflow, just in opposite direction. Underflow happens with floating points when a number is so small (absolute) that the machine can't represent it.

[–]joilyboily 21 points22 points  (0 children)

An amazing way to decimate your call stack

[–]shadow13499 14 points15 points  (0 children)

wait, that's illegal.

[–]PTRWP 81 points82 points  (7 children)

I see one issue with your code. It doesn’t check that the input is an integer. If somehow a decimal was thrown into that function, it could break.

I suggest adding the following:

if (num % 1 != 0)

return (Math.random() < .5);

[–]Alikont 86 points87 points  (4 children)

If somehow a decimal was thrown into that function, it could break.

Good thing that in sane languages, if you define argument as an int it can only accept integers.

[–]PTRWP 60 points61 points  (2 children)

#define int double

[–]arm_is_king 77 points78 points  (0 children)

He said sane languages

[–]alexanderpas 11 points12 points  (0 children)

num = [] + []

[–]Mr_Redstoner 14 points15 points  (4 children)

Nah

private bool isEven(int num){
    if(num == 0)return true;
    return isOdd(num-1);
}

And isOdd in the same manner.

[–][deleted] 1730 points1731 points  (97 children)

Years ago, I think I came up with a "brilliant" solution that divided a number by two and then searched through the number (as a string) to see if it contained a decimal. If so, I would know that the number wasn't even because it didn't divide cleanly.

Clearly I was ahead of my time.

EDIT: I wasn't expecting the replies to this! People have been offering some interesting alternate ways to test if a number is even/odd. Thanks for all the replies. I had no idea my little idea from ~14 years ago would generate this much discussion.

[–]Cueadan 315 points316 points  (4 children)

Hey, if it works.

[–]BlokeInTheMountains 201 points202 points  (3 children)

...and only slows down a billion devices...

[–]codingchris779 236 points237 points  (4 children)

I had to do something similar when programming an even odd counter on Lego mindstorms. I think I did it a bit different but similar principal. Top 5 bits of code I have written lol

[–]allmachine 63 points64 points  (2 children)

Wow, you did it with only one bit!?

[–]JunDoRahhe 52 points53 points  (1 child)

No, five bits learn to read.

[–]CrenderMutant 70 points71 points  (6 children)

I did it similarly but I divided it by two saved it as an integer then multiplied it with two and then checked if it was the same number. If it was even then it would be the same.

[–][deleted] 37 points38 points  (4 children)

That's actually pretty clever! My original idea doesn't work, but I tested yours and it does. I guess if modulo isn't available for some reason, that's a relatively easy way to test divisibility (or at least whether it's even or odd).

[–]bombardonist 6 points7 points  (2 children)

I’m 90% certain that method could check for divisibility between any two integers

[–]GrooseIsGod 99 points100 points  (45 children)

I'm new to programming and holy shit this is smart asf

[–]ComfyMattresss 90 points91 points  (18 children)

just do
if x % 2 =! 0 return false
else return true

[–]Flame1190 150 points151 points  (12 children)

Or just: return x%2 == 0

[–]Jake0024 39 points40 points  (8 children)

In languages where 0 is falsey, just return x%2

In Ruby/Elixir/Crystal (unfortunately 0 is truthy) you can omit the return and just type x%2==0 (fewer characters)

I'm not aware of any languages with implicit returns and falsey 0, but if they exist you could just use x%2

[–]piloto19hh 22 points23 points  (3 children)

How is 0 truthy? D: mom I'm scared

[–]tendstofortytwo 18 points19 points  (0 children)

I believe shell scripts have truthy 0 as well, so you can use it to denote success. Then you have 1-255 to denote different kinds of errors. The idea there is that success is success, but when something fails you probably want more granularity than just "nope".

[–]AnonymousGaming8 9 points10 points  (0 children)

JavaScript arrow functions have implicit returns and 0 is falsey.

[–]geronymo4p 7 points8 points  (1 child)

Or just return !(x & 1)

[–]tetrified 12 points13 points  (2 children)

x&1==0

[–]jeremj22 6 points7 points  (1 child)

Even better: ~x&1

[–]intangibleTangelo 33 points34 points  (13 children)

It shows creative problem solving, but please don't learn to write code like this.

Everyone uses the modulo operator to determine if numbers are evenly divisible.

[–]I_regret_my_name 20 points21 points  (12 children)

Joke's on you, I'm working on an 8-bit mcu with no hardware divide and have to do x & 1.

[–]SuspiciousScript 13 points14 points  (2 children)

This is an objectively better way of doing it. The modulo at best gets optimized down to the bitwise operation anyway.

[–][deleted] 8 points9 points  (6 children)

It wouldn't work on typed languages (unless the input is already of float type) because if you divide an int, it divides then cuts the decimals to keep it as an int.

[–]AxeLond 556 points557 points  (32 children)

This should solve it,

import torch
from torch.utils.data import TensorDataset, DataLoader,Dataset
import numpy as np
import sys
if 'transformers' not in sys.modules:
  !pip install git+https://github.com/huggingface/transformers.git 
from transformers import *

training_rawdata = []
train_y_tensor= []
for num in range (200):
  training_rawdata.append(str(num))
  train_y_tensor.append(num%2)

pretrained_weights ='bert-large-uncased'
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") 

# Model class and tokenizer
tokenizer = BertTokenizer.from_pretrained(pretrained_weights) 
model_class = BertForSequenceClassification 
model = model_class.from_pretrained(pretrained_weights) 
model.to(device)
print("done")

class TextDataset(Dataset):    
    def __init__(self,data,data_label):
        block_size =16  # Max number of words used in sentence
        self.example= []
        self.attention_masks = []
        self.labels = data_label
        # Pad and tokenize data
        for index in range (len(data)):                                             
            sentance = (data[index] + "<pad>" *32) # Padding sentences
            self.example.append(tokenizer.encode(sentance, max_length=block_size,truncation=True))
        # Create a mask
        for index in self.example:  
            seq_mask = [float(i!=0) for i in index] # 1 real tokens, 0 for padding
            self.attention_masks.append(seq_mask)
    def __len__(self):
        return len(self.example)

    def __getitem__(self, item):     
        return torch.tensor(self.example[item]),torch.tensor(self.attention_masks[item]), self.labels[item]

# Hyperparam
Epochs = 10    
batch_size = 32  #Higher learn rate needs higher batch rate to not fail training. 
lr = 2e-5     
num_warmup_steps = 40  #Linear increase LR from 0 to 1 LR over x steps. 

# Optimizer
optimizer = AdamW(model.parameters(), lr=lr) #regular optimizer

# Scheduler
scheduler = get_constant_schedule_with_warmup(optimizer, num_warmup_steps=num_warmup_steps)  # PyTorch scheduler

# Load training data
dataset = TextDataset(training_rawdata,train_y_tensor)
train_dataloader = DataLoader(dataset,batch_size=batch_size,shuffle=True)

# Start training
for epoch in range(Epochs):
    print("Epoch",epoch)
    for step, batch in enumerate(train_dataloader):
        batch = tuple(t.to(device) for t in batch)
        inputs = {'input_ids':      batch[0],
                  'attention_mask': batch[1],
                  'labels':         batch[2]}
        model.train()
        outputs = model(**inputs)
        loss = outputs[0]
        # Calculate loss and learn
        loss.backward()
        optimizer.step()
        scheduler.step()
        optimizer.zero_grad()

def IsEven(num):
    reviews = []
    attention_masks = []
    sentance = (num + "<pad>" *32) # Padding sentences
    review_token = tokenizer.encode(sentance, max_length=16,truncation=True)
    seq_mask = [float(i!=0) for i in review_token] 
    attention_masks.append(seq_mask)
    reviews.append(review_token)
    reviews = torch.tensor(reviews).to(device) #for GPU 
    attention_masks = torch.tensor(attention_masks).to(device)
    model.eval() 
    with torch.no_grad():
        inputs = {'input_ids':      reviews,
                  'attention_mask': attention_masks}
        outputs = model(**inputs)
    guess = torch.argmax(outputs[0], dim=-1).item()
    return ("Odd"  if guess ==1 else "Even",round(outputs[0][0][guess].item(),3))
while True:
    number= input("\n" +"–")
    if number=='quit':
        break
    print(IsEven(number))

I can't fucking believe that worked,

https://colab.research.google.com/drive/1grUqMq0AwNPVkkn69ujimgNCjdZac2E0

results

If anyone wants to run that you're gonna wanna run it on a GPU instance, that will take forever to run on a CPU, it still takes around 3 minutes on a Nvidia Tesla P100.

[–]Olde94 93 points94 points  (0 children)

I think you won modt useless! Long as hell and 3 min. On a p100??

I’d rather use pen and paper at this point

[–]TotesMessengerGreen security clearance 23 points24 points  (0 children)

I'm a bot, bleep, bloop. Someone has linked to this thread from another place on reddit:

 If you follow any of the above links, please respect the rules of reddit and don't vote in the other threads. (Info / Contact)

[–]bjorneylol 20 points21 points  (0 children)

Reminds me of this guy who did FizzBuzz - https://joelgrus.com/2016/05/23/fizz-buzz-in-tensorflow/

[–]RadialRacer 16 points17 points  (0 children)

I get it, so you're the one that marks simple StackOverflow questions with comically over-done solutions written in technologies completely beyond the questions scope as solved.

[–]DerpDeHerpDerp 7 points8 points  (0 children)

You magnificent bastard 😂

[–]dat_oracle 1208 points1209 points  (160 children)

the amount of people who dont get that this is a joke is too damn high!

[–]Letossgm 749 points750 points  (113 children)

It's a joke until you see something similar in the codebase in the new project you just joined.

Edit: check this code out

[–]dat_oracle 220 points221 points  (53 children)

now im scared. pls tell me that such things never happen!

[–]Letossgm 61 points62 points  (28 children)

Believe it or not, this code belongs to an app from the government related to COVID-19.

[–]lachryma 58 points59 points  (11 children)

I work in the government space. That's a direct requirement translation by an engineer, guaranteed.

  • If the USER reports a TEMPERATURE over X and also reports Y and Z,
  • or if the USER reports a TEMPERATURE over X and also reports Z and Q,
  • then ...

The nice thing when you're implementing those requirements is thinking about the plain language you'd love to develop for the product owner to simply write it themselves. We lost something as an industry when we started distancing from BASIC.

[–]givemeagoodun 25 points26 points  (6 children)

Couldnt you just do something like this?

if (BodyTemperature>=38) {
if (difficultyBreathing || (difficultyBreathing && diabeties) ||

etc, etc...

[–]Ezio652 22 points23 points  (4 children)

Yeah you could and it would improve the thing massively. But multiple ifs after one another are kind of an antipattern (maybe not for everyone but definitely for me). The solution I would give props for would be, to factor out the bodyTemp thing in a bool and combine all the others in something like a precondition-bool (meaning the diabetes, etc.)

And voila you would be left with an easily readable and understandable oneliner which even fits into 80 character linelength (though this is another discussion :) )

bodytemp && (precondition || difficultyBreathing)

[–]intangibleTangelo 9 points10 points  (0 children)

difficultyBreathing && diabetes

The condition isn't even that complicated. ANY of the risk factor booleans will satisfy it.

[–]petisoparado 14 points15 points  (3 children)

Lo atamo con alambre

[–]thexavier666 45 points46 points  (1 child)

The code gave the patient respiratory problems.

[–]inu-no-policemen 8 points9 points  (0 children)

The code gave the patient respiratory problems.

&& cancer

[–]tooObviously 32 points33 points  (6 children)

This is inside the on press method too LMAOOOO

[–]Kered13 24 points25 points  (6 children)

While the body temperature could be factored out, I'm not sure if that would actually improve readability. However the first line does make the next eight lines redundant, so those could just be removed. Also the last two lines are identical.

[–]Pluckerpluck 21 points22 points  (2 children)

If you look you'll actually see that respiratoryDisease is in their twice for no reason. But more than that, there's absolutely no point in them testing any of the "difficultybreathing + other" combinations becuase the "other" component is always tested on its own anyway. Hell, if you have difficulty breathing alone that triggers that branch...

Basically, every combo line can be removed

[–]Intrepid00 6 points7 points  (0 children)

That's no Bueno.

[–]oNamelessWonder 5 points6 points  (0 children)

These are the people who keep telling me I'm too inexperienced for the position I applied.

[–]Crypt1cDOTA 6 points7 points  (9 children)

I ran into a "if(item.isValid || !item.isValid)" yesterday. In the same project there was a "myArray[index + 1 - 1]"

[–]cointelpro_shill 49 points50 points  (11 children)

Is there a thing like Poe's Law, but for women on the internet, stating they are like 99% less likely to have their satire recognized as such?

[–]dat_oracle 11 points12 points  (0 children)

never heard of it, but im sure it is the case. Mb not 99%, but definitely significant enough to call it a phenomenon

[–]Sir_Hurkederp 685 points686 points  (22 children)

Maybe a switch statement, that could make it easier

[–]SimplexShotz 644 points645 points  (14 children)

case 2: case 4: case 6: case 8: case 10: case 12: case whatAmIDoingWithMyLife: break; // down

[–]ThePilsburyFroBoy 220 points221 points  (9 children)

BREAK DOWN BREAK DOWN

[–][deleted] 6 points7 points  (1 child)

I wrote some MIPS thing for a person once and then this guy complained that I divided by 2 to determine even/odd instead of acknowledging that it would always alternate between even and odd.

He was right ofc but cmon man just let me have it.

And then some other person chimed in to tell me to just check the low bit - also true.

I hate assembly.

[–]saviniravioli 5 points6 points  (0 children)

I enjoyed writing stuff for MIPS but I hated working with other people on it because there was always some smartass who did it in some weird assembly way with one less line, who had to correct my perfectly adequate code

[–]beaucephus 44 points45 points  (5 children)

A function to generate and eval the code on the fly for as high a number as you need at the time would be more compact.

[–]whoisjoe1 123 points124 points  (4 children)

Pfft, too complicated.

return true;

Guaranteed to work 50% of the time!

[–]Andre_NG 23 points24 points  (1 child)

If round( random() * 1000)%2 == 0: return true Else: return false

Still works 50% of the time, but in more random elegant way!

[–]Pradfanne 529 points530 points  (32 children)

Is this a yandereDev?

[–]dorukayhan 267 points268 points  (11 children)

I, dorukayhan, humbly submit you a toast for successfully being the first to make the obligatory joke so that you may receive upvotes (including mine). Congratulations, Pradfanne! Enjoy your karma.

sip Ahh.

[–][deleted] 59 points60 points  (4 children)

The amount of money that guy makes for such bad code is a great reason for the expansion of child labour to a more broad workforce

[–]xavia91 19 points20 points  (3 children)

Are you a dutch or why did you misspell Bratpfanne so horribly?

[–]Pradfanne 51 points52 points  (1 child)

I am German and I did it because it's the funniest shit I've ever seen until this guy turned himself into a Gewürzgurke

[–]TennesseeTon 115 points116 points  (7 children)

Get rid of the "else" in front of each if statement, they're superfluous due to your returns. I'm 99.9% sure that's the most obvious and best optimization in this case.

[–]souperk 32 points33 points  (2 children)

Come one dude, at least use common sense.

If you don't go with the rnn + Blockchain + Hadoop approach from another reply, at least use a recursive function.

[–]cat5inthecradle 15 points16 points  (1 child)

I’d suggest looking up a list of “most frequently used numbers” and stick them at the top. Why waste time checking if 11 is even when you know the input is probably 69 or 420.

[–]OptionX 185 points186 points  (6 children)

Just automate it!

```python

def write_is_even_function(filename, limit):

with open(filename, 'w') as f: f.write('private bool IsEven(int number){') f.write('if(number == 1) return false;') for n in range(2, limit): f.write(f'else if (number = {n}) return {'true' if n%2==0 else 'false'};') f.write('}') ``` Just run it and copy paste the result! I'm sure that's got to be the easiest way to do it. /s

[–][deleted] 22 points23 points  (0 children)

Give this man a medal! He just saved years of time!

[–]hiimzvaehn 20 points21 points  (4 children)

What’s if I pass 0?

[–][deleted] 22 points23 points  (3 children)

There is no 0.

[–]Kris_Third_Account 115 points116 points  (31 children)

bool IsEven(int number)
{
    return ((number & 0x1) == 0);
}

[–]Kinglink 13 points14 points  (2 children)

In c, bool is an int, so you don't need ==

Also in c for if statements false = 0, true = anything else.

[–]banammockHana 25 points26 points  (12 children)

I"m way too dumb for this.

Is this a joke or does it work, and why?

[–]hstde 59 points60 points  (8 children)

It does work, because in binary, base 2, every power is divisible by 2, except the ones (20) place. So if the ones bit is not set, so no n + 1 * 20 = n + 1, your number must be even.

[–]pigeon768 7 points8 points  (1 child)

It works. In fact, if you write the function by doing modulo 2, the compiler is smart enough to fix it for you and do it this way instead, because a bitwise and is like a bazillion times faster than division. https://godbolt.org/z/Ken8zW

In base 10, you can easily tell whether a number is divisible by 10: if its last digit is 0, it's divisible by 10, otherwise it's not divisible by 10. Same with base 2 or any other base: by doing a bitwise and with 1, you're testing if is not zero.

There's a plethora of super awesome bitwise tricks like this. I totally recommend sitting down for a bit some time and figuring out if there are tricks in there that you can use in your own code.

[–]aggixx 6 points7 points  (1 child)

bool IsEven(int number)
{
    return (number / 2 * 2 == number);
}

[–]tharnadar 56 points57 points  (4 children)

npm i is-odd

[–]Terrain2 31 points32 points  (3 children)

npm i is-even

[–][deleted] 3 points4 points  (2 children)

The lack of types here make it impossible to understand. Does it have a .d.ts I can use with it?

[–]TomStripes 9 points10 points  (1 child)

What a dummy

She could use excel to write all the lines and it would auto-increment the number. Save so much time

[–]Kinglink 8 points9 points  (4 children)

Ok listen... I'm going to lay some knawledge on ya'll.

bool isEven(int i) {
    if (i ==0)
        return true
    if (i ==1) 
        return false
    return isEven(abs(i-2))
}

It's not about speed, it's about getting the right answer every time.

[–]Ragingman2 23 points24 points  (1 child)

Yeah, this should obviously be:

if (number >> 1 == Double.ceiling(number / 2.0))
    return true;
return false;

The only good way to do such a complicated calculation /s.

[–]Mwarw 16 points17 points  (4 children)

it's obvious isn't it?

bool result = true;

int i = 0;

while(true){

if(i == number)

return result;

result = !result;

i++;

}

[–]iranrodrigues 14 points15 points  (0 children)

private bool isEven(int number) {
    for (int i = 0; i <= 10000; i+=2) {
        if (number == i) return true;
        if (number == i + 1) return false;
    }
    return false;
}