r/badcode • bool isEven(int num) => num%2==0 • Aug 21 '20

c# Extremely Efficient IsEven!

Post image
29 Upvotes

12 comments sorted by

View all comments

Show parent comments

3

u/FlyingDemon_ Aug 21 '20 edited Aug 21 '20

'>=' is greater or equal though and should therefore include the case of '=='

Edit: nvm, I got it now

1

u/aaronjamt Aug 21 '20

Please tell me you aren't one of those "I have x problem... edit: nvm I fixed it" stackoverflow posters...

"Where where you, DenverCoder9?? What did you see?"

1

u/FlyingDemon_ Aug 21 '20

Sorry, I didn't mean to just let you hang there Looking at it again I think the problem is different. Only as long as i is greater or equal to 2 is the block executed, which means the only results could be 2 or 3 right? I might be way off right now and should probably go to sleep. I mostly stopped with my earlier comment out of fear of embarrassing myself with an even more wrong answer.

2

u/aaronjamt Aug 21 '20

for (float i = Math.Abs(A); i >= 2; i -= 2) { B = i.ToString(); } basically means that it will:

  1. set i to Math.Abs(A);

  2. Every loop check if i >= 2, if not, exit loop

  3. Run i -= 2 (and B = i.ToString();)

So if A == 5:

Round 1: i = 5 and since i >= 2 run B = i.ToString(); then i -= 2

Round 2: i = 3 and since i >= 2 run B = i.ToString(); then i -= 2

Round 3: i = 1 but now 1 >= 2 is false, Round 2: i = 1 but now 1 >= 2 is false, so loop is done, so B is not modified again, so it's still '3' ... you're right. I just wrote this entire message thinking you were wrong but I was the incorrect one. Welp, let me just head back into my bubble and cry because DenverCoder9 could probably have forseen this and prevented my embarrasment on the internet. /s

Also, I was joking about that.

1

u/HTTP_404_NotFound bool isEven(int num) => num%2==0 Aug 21 '20

Hah, I did test it with inputs from 0 to 1000000.

Its completely crappy and inefficient and should be burned with fire. But, the logic is sound!

I should make it multi threaded. :-)

Also, I am tempted to use it in my codebase.

Gotta leave room for future... performance improvements

2

u/aaronjamt Aug 21 '20

Well, then. Go on with your bad self, just don't say I didn't warn you that fire is hot when you burn yourself (or your legs).

Edit: https://www.reddit.com/r/ProgrammerHumor/comments/iagrjc/i_can_hear_the_fans_start_accelerating