How to determine if a number is odd or even without mod -or- bitwise operations?

  • How to determine if a number is odd or even without mod -or- bitwise operations?



    This challenge is grossly inefficient, but challenges your ability to think outside the box for a creative solution.



    EDIT:



    Please create a function. Also, while regex is a fun response, the function should accept any valid number.



    BACKGROUND:
    This question stems from my earliest programming days. The homework for our first day of class was to write a simple program that printed 'odd' or 'even'. Being the brat I was, I didn't read the book we had for the class where it simply showed us how to use % to determine that. I spent about a half hour pacing back in forth in my room trying to think of a way to do this and had remembered from the lecture that numbers can lose and gain precision as they are cast from one primitive type to another. Therefore, if you took the number, divided it by two and then multiplied it back didn't equal the original number, then you would know that the number was odd.



    I was stunned the next day, while our instructor was evaluating our programs, that he thought that it was the most original, if inefficient, way of solving the problem.


    Should we create a function or a program? How should IO happen if we have to do a program? Please, elaborate further.

    What objective criterion will determine the accepted answer? Code size? Something else?

    Is it definitely a number? Should it give false positives for a string?

    This has been around for quite a long time, but there doesn't seem to be a winning condition of any kind, which to my mind means there is no game here.

  • fR0DDY

    fR0DDY Correct answer

    10 years ago

    In most programming languages division returns quotient for integers. So you can simply check this



    (i/2)*2==i

    Not necessarily most, I'd say. Many, maybe.

    to ensure it runs properly, you need to make sure you cast everything into an `int`/`long` type

    @warren Depends on the programming language/compiler optimizations/etc. Additionally, you can use `floor()`. That works perfectly in C and C++.

    I marked yours as the answer because it had the widest usability in different languages. It also happened to be the solution I came up with eons ago to solve the same problem. :)

    Is 0 a even number?

    @userunknown: Yes, zero is even.

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM