20
\$\begingroup\$

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.

\$\endgroup\$
4
  • 3
    \$\begingroup\$ Should we create a function or a program? How should IO happen if we have to do a program? Please, elaborate further. \$\endgroup\$
    – Champo
    Apr 28, 2011 at 3:10
  • 2
    \$\begingroup\$ What objective criterion will determine the accepted answer? Code size? Something else? \$\endgroup\$ Apr 28, 2011 at 3:47
  • \$\begingroup\$ Is it definitely a number? Should it give false positives for a string? \$\endgroup\$
    – William
    Apr 30, 2011 at 1:22
  • \$\begingroup\$ 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. \$\endgroup\$ Mar 16, 2013 at 19:22

50 Answers 50

72
\$\begingroup\$

Python

print('even' if (-1)**n==1 else 'odd')
\$\endgroup\$
3
  • 11
    \$\begingroup\$ The simple beauty / beautiful simplicity of mathematics...very nice! \$\endgroup\$
    – jscs
    Apr 28, 2011 at 16:15
  • \$\begingroup\$ I like this one a lot. \$\endgroup\$
    – Rob
    Oct 11, 2011 at 19:21
  • \$\begingroup\$ Slow but creative. \$\endgroup\$ Nov 1, 2011 at 23:31
40
\$\begingroup\$

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

(i/2)*2==i
\$\endgroup\$
6
  • 6
    \$\begingroup\$ Not necessarily most, I'd say. Many, maybe. \$\endgroup\$
    – Joey
    Apr 28, 2011 at 10:25
  • 1
    \$\begingroup\$ to ensure it runs properly, you need to make sure you cast everything into an int/long type \$\endgroup\$
    – warren
    Apr 28, 2011 at 13:23
  • \$\begingroup\$ @warren Depends on the programming language/compiler optimizations/etc. Additionally, you can use floor(). That works perfectly in C and C++. \$\endgroup\$ May 1, 2011 at 21:03
  • 1
    \$\begingroup\$ Is 0 a even number? \$\endgroup\$ Aug 13, 2011 at 23:58
  • 4
    \$\begingroup\$ @userunknown: Yes, zero is even. \$\endgroup\$ Nov 5, 2011 at 18:40
21
\$\begingroup\$

Brainf*** (179)

This is one of the more interesting problems involving conditional logic that I have done in BF.

+[>,]<--------------------------------------->>+++++[>+++++++
++++++>+++++++++++++++<<-]>++++>++++<<+<+<-[>-<-[>+<-[>-<-[>+<-[>-<-[>
+<-[>-<-[>+<-[>-<[-]]]]]]]]]]>[>>>.<<-<-]>[>.<-]

It takes a text input with a number. If the number is even, it outputs E, and if it is odd, it outputs O.

I'm proud enough of it that I'll show off a more human readable form:

+[>,]                                                   steps through input until it reaches eof.
<---------------------------------------                gets the numerical value of the last digit
>>+++++[>+++++++++++++>+++++++++++++++<<-]>++++>++++    store E and O
<<+<+<                                                  store a bit indicating parity, and a temporary bit
-[>-<                                                   !1
  -[>+<                                                 && !2
    -[>-<                                               && !3
      -[>+<                                             && !4
        -[>-<                                           && !5
          -[>+<                                         && !6
            -[>-<                                       && !7
              -[>+<                                     && !8
                -[>-<[-]]                               && !9
              ]
            ]
          ]
        ]
      ]
    ]
  ]
]
>[>>>.<<-<-]>[>.<-]                                     Display E or O based on the value of the parity bit.
\$\endgroup\$
21
\$\begingroup\$

Mathematica

SawtoothWave[x / 2] == 0
Exp[I Pi x] - 1 == 0
Sin[5 x / Pi] == 0
\$\endgroup\$
3
  • 2
    \$\begingroup\$ Can you split these two solutions into different answers? \$\endgroup\$
    – FUZxxl
    Apr 28, 2011 at 8:00
  • \$\begingroup\$ Aren't those four solutions? \$\endgroup\$
    – Joey
    Apr 28, 2011 at 8:47
  • \$\begingroup\$ Actually, all built-in names in Mathematica are capitalized, so as funny as it looks, you should use I and Pi instead of i and pi. \$\endgroup\$ Jul 24, 2015 at 1:06
16
\$\begingroup\$

C

Multiplied by itself a few times any even number will overflow to 0 given a finite size integer, and any odd number will continue to have at least the least significant bit set.

#include "stdio.h"
long long input=123;
int main(){
    int a;
    for(a=6;a;a--){
        input*=input;
    }
    if(input){
        printf("Odd");
    }
    else{
        printf("Even");
    }
    return 0;
}

Edit: As a simple function:

int isOdd(long long input){
    int a;
    for(a=6;a;a--){
        input*=input;
    }
    return !!input;
}
\$\endgroup\$
1
  • \$\begingroup\$ Be sure to use unsigned integers. Overflow of signed integers is undefined behavior in C, so optimization could do something weird if it wanted. \$\endgroup\$
    – Joey Adams
    Sep 10, 2011 at 8:57
13
\$\begingroup\$

JavaScript

/[02468]$/.test(i)

yields true for an even number. This only works with reasonably sized integers (e.g. not scientific notation when converted to a string and not having a fractional part.)

\$\endgroup\$
3
  • 3
    \$\begingroup\$ To meet the "function" requirement you could change it to simply /[02468]$/.test. \$\endgroup\$
    – Ry-
    Apr 28, 2011 at 18:12
  • \$\begingroup\$ It wasn't exactly clear in the question but it could be possible that the input isn't a number at all, /[02468]$/.test('I am a fake even number 0'). In that case you could do /^[0-9].[02468]$/.test(i) \$\endgroup\$
    – William
    Apr 30, 2011 at 1:23
  • \$\begingroup\$ /-?^\d*[02468]$/ would be a little stricter than your regex. You would need more work for this to work properly for numbers that are toString'ed using scientific notation. \$\endgroup\$ Aug 26, 2011 at 19:32
13
\$\begingroup\$

Python (Slow)

n=1234
while n > 1: n -= 2 #slow way of modulus.
print "eovdedn"[n::2]
\$\endgroup\$
4
  • 1
    \$\begingroup\$ Works for positive...i suppose i could add a abs() call in the beginning. \$\endgroup\$
    – st0le
    Apr 28, 2011 at 4:34
  • \$\begingroup\$ @Josh: That trick appeared here a few times already by now :) \$\endgroup\$
    – Joey
    Apr 28, 2011 at 10:25
  • \$\begingroup\$ Credits to gnibblr :) \$\endgroup\$
    – st0le
    Apr 28, 2011 at 11:21
  • \$\begingroup\$ @Joey: I didn't figure it was new, but style doesn't have to be original. :) \$\endgroup\$
    – jscs
    Apr 28, 2011 at 15:36
12
\$\begingroup\$

Python

Since I'm not really sure what the scoring criteria are, here's a bunch of solutions I've come up with for amusement's sake. Most of them use abs(n) to support negative numbers. Most, if not all, of them should never be used for real calculation.

This one is kind of boring:

from __future__ import division
def parity(n):
    """An even number is divisible by 2 without remainder."""
    return "Even" if n/2 == int(n/2) else "Odd"

def parity(n):
    """In base-10, an odd number's last digit is one of 1, 3, 5, 7, 9."""
    return "Odd" if str(n)[-1] in ('1', '3', '5', '7', '9') else "Even"

def parity(n):
    """An even number can be expressed as the sum of an integer with itself.
      
    Grossly, even absurdly inefficient.
    
    """
    n = abs(n)
    for i in range(n):
        if i + i == n:
            return "Even"
    return "Odd"

def parity(n):
    """An even number can be split into two equal groups."
    g1 = []
    g2 = []
    for i in range(abs(n)):
        g1.append(None) if len(g1) == len(g2) else g2.append(None)
    return "Even" if len(g1) == len(g2) else "Odd"

import ent # Download from: http://wstein.org/ent/ent_py
def parity(n):
    """An even number has 2 as a factor."""
    # This also uses modulo indirectly
    return "Even" if ent.factor(n)[0][0] == 2 else "Odd"

And this is my favorite although it unfortunately doesn't work (as pointed out by March Ho below: just because all even numbers are the sum of two primes, doesn't mean that all odd numbers aren't).

import itertools
import ent    # Download from: http://wstein.org/ent/ent_py
def parity(n)
    """Assume Goldbach's Conjecture: all even numbers greater than 2 can
    be expressed as the sum of two primes.
        
    Not guaranteed to be efficient, or even succeed, for large n.
    
    """
    # A few quick checks
    if n in (-2, 0, 2): return "Even"
    elif n in (-1, 1): return "Odd"
    if n < 0: n = -n    # a bit faster than abs(n)
    # The primes generator uses the Sieve of Eratosthenes
    # and thus modulo, so this is a little bit cheating
    primes_to_n = ent.primes(n)
    # Still one more easy way out
    if primes_to_n[-1] == n: return "Odd"
    # Brutish!
    elif n in (p1+p2 for (p1, p2) in itertools.product(primes_to_n, primes_to_n)):
        return "Even"
    else:
        return "Odd"
\$\endgroup\$
3
  • \$\begingroup\$ Cute solutions :-) \$\endgroup\$
    – Joey
    May 4, 2011 at 14:42
  • 2
    \$\begingroup\$ Really an old necro, but doesn't your Goldbach's conjecture answer print Even for 9? Seems like a case of affirming the consequent fallacy \$\endgroup\$
    – March Ho
    Jul 24, 2015 at 1:27
  • \$\begingroup\$ Yup, you're absolutely, one hundred percent right, @MarchHo. Egg on my face. \$\endgroup\$
    – jscs
    Jul 24, 2015 at 1:33
10
\$\begingroup\$

Haskell

This is, of course, in no way the creative, thinking-outside-the-box solution you're looking for, but how many times am I going to get to post a Haskell answer shorter than GolfScript, really? It's really a shame this isn't a code golf.

odd

But more seriously:

data Parity = Even | Odd
            deriving (Show)

parity = p evens odds
  where p (x:xs) (y:ys) i | i == x = Even
                          | i == y = Odd
                          | otherwise = p xs ys i
        evens = interleave [0,2..] [-2,-4..]
        odds = interleave [1,3..] [-1,-3..]
        interleave (x:xs) ys = x : interleave ys xs
\$\endgroup\$
4
  • \$\begingroup\$ looks longer than the GolfScript answer to me \$\endgroup\$
    – warren
    Apr 28, 2011 at 13:26
  • 2
    \$\begingroup\$ I was referring to the first block (odd) which is a builtin function that returns True if the number is odd. That's a complete answer on its own and shorter than the current GolfScript answer (which at the time of writing this is 10 chars, but I expect that to go down). The question is also a bit underspecified, which is why I assert that odd is sufficient. That may change as well. \$\endgroup\$
    – user1011
    Apr 28, 2011 at 16:02
  • 1
    \$\begingroup\$ missed the first reply in your answer :) \$\endgroup\$
    – warren
    Apr 28, 2011 at 16:23
  • 1
    \$\begingroup\$ At the very least the parity algorithm works on all Num instances that are integers. That's hot! Though I probably would have done evens = [0,2..] >>= \n -> [-n, n]. Similar for odds. \$\endgroup\$ Aug 26, 2011 at 19:38
7
\$\begingroup\$

Using a deliberately perverse reading of the question, "How to determine if a number is odd or even", here's a C implementation (assume bool and true are defined appropriately):

bool is_odd_or_even(int n)
{
    return true;
}
\$\endgroup\$
1
  • \$\begingroup\$ The question mentions number, not integer. Number like 0.5 returns true when it shouldn't. \$\endgroup\$
    – 0..
    Mar 18, 2014 at 19:19
7
\$\begingroup\$

What, no randomized algorithms yet??

C

#include<stdio.h>
#include<stdlib.h>

void prt_parity_of(int n){
  int i,j=2;
  char o[]="eovdedn"
     , f[n=abs(n)]; for(i=n;i-->0;f[i]=1);

  while(j>1){
    while((i=rand()%n)
       == (j=rand()%n)
       || (f[i]&f[j]>0)
       && (f[i]=f[j]=0)
    );for(i=j=0; ++i<n; j+=f[i])
  ;}for(;j<7;j+=2)putchar(o[j]);
}

Randomly pairs numbers in the range 0..n-1 until less than 2 are left. It's quite amazingly inefficient: O(‌n3).


Completely different:

Haskell

import Data.Complex

ft f = (\ω -> sum[ f(t) * exp(0:+2*pi*ω*t) | t<-[-1,-0.9..1] ] )

data Parity = Even | Odd deriving (Show)

parity n
  | all (\(re:+im) -> abs re > abs im) [ft ((:+0).(^^n)) ω | ω<-[0..20]]  = Even
  | otherwise                                                             = Odd

Uses the fact that the Fourier transform of an even function (e.g. \x->x^^4) is real, while the Fourier transform of an odd function is imaginary.

\$\endgroup\$
6
\$\begingroup\$

Coq, 103

Fixpoint even n:=match n with O=>true|S n=>odd n end with odd n:=match n with O=>false|S n=>even n end.

As far as I can tell this is the first coq entry on codegolf.

Even shorter (59):

Fixpoint even n:=match n with O=>true|S n=>negb(even n)end.
\$\endgroup\$
5
\$\begingroup\$

Windows PowerShell

function OddOrEven([long]$n) {
  if (0,2,4,6,8 -contains "$n"[-1]-48) {
    "Even"
  } else {
    "Odd"
  }
}
  1. Convert to string
  2. Pick last letter (digit) (essentially a mod 10).
  3. Check if it is 0, 2, 4, 6 or 8.

No bitwise operators, no modulus, as requested.

\$\endgroup\$
4
\$\begingroup\$

Ruby

n.odd?

If you want to print out the result:

f[n] = ->(n){puts n.odd?? 'odd' : 'even'}
\$\endgroup\$
1
  • \$\begingroup\$ I'm fairly use ruby uses mod in the .odd? definition. \$\endgroup\$
    – MrZander
    Mar 15, 2013 at 23:49
4
\$\begingroup\$

Unlambda

The world needs more Unlambda.

Unlambda has a killer advantage here: its default (ahem) representation for numbers are Church numerals, so all that's needed is to apply them to function binary-not to function true. Easy!

PS: Markdown and Unlambda are definitely not made for one another.

true  = i
false = `ki
not   = ``s``s``s`k``s``si`k`kk`k`kii`k`ki`ki
even? = ``s``si`k``s``s``s`k``s``si`k`kk`k`kii`k`ki`ki`ki

Verification for the first few integers:

```s``si`k``s``s``s`k``s``si`k`kk`k`kii`k`ki`ki`ki`ki                   => i
```s``si`k``s``s``s`k``s``si`k`kk`k`kii`k`ki`ki`kii                     => `ki
```s``si`k``s``s``s`k``s``si`k`kk`k`kii`k`ki`ki`ki``s``s`kski           => i
```s``si`k``s``s``s`k``s``si`k`kk`k`kii`k`ki`ki`ki``s``s`ksk``s``s`kski =>`ki
\$\endgroup\$
3
\$\begingroup\$

Golfscript

~,2/),1=\;
\$\endgroup\$
3
\$\begingroup\$

Python

print (["even"] + (["odd", "even"] * abs(n)))[abs(n)]

Similar performance to the earlier version. Works for 0 now.

Incorrect Earlier version:

print ((["odd", "even"] * abs(n))[:abs(n)])[-1]

Not particularly efficient; time and memory both obviously O(n): 32 msec for 1,000,000; 2.3 msec for 100000; 3.2 usec for 100. Works with negative numbers. Throws an error for 0, because 0 is neither even nor odd.

\$\endgroup\$
2
  • 3
    \$\begingroup\$ Zero is definitely even. See also: en.wikipedia.org/wiki/Parity_of_zero \$\endgroup\$
    – user1011
    Apr 28, 2011 at 7:14
  • \$\begingroup\$ @jloy: Aw, crap. I thought that was "a feature, not a bug". More revisions... \$\endgroup\$
    – jscs
    Apr 28, 2011 at 7:16
3
\$\begingroup\$

Fractran

[65/42,7/13,1/21,17/7,57/85,17/19,7/17,1/3]

applied to

63*2^abs(n)

yields either 5 if n is odd or 1 if n is even.

Update: Much shorter but not so interesting:

[1/4](2^abs(n))

is 2 for odd n and 1 for even n.

\$\endgroup\$
3
\$\begingroup\$

MMIX (4 Bytes)

This is kind of cheating. I use neither mod nor bit fiddling operations. It's rather that testing for odd / even numbers is builtin. Assuming that $3 contains the number to test and the result goes into $2:

ZSEV $2,$3,1

sets $2 to 1 if $3 is even and to 0 if not. The mnemnoric ZSEV means zero-set even and has the following semantics:

ZSEV a,b,c: if (even b) a = c; else a = 0;

For the above line, mmixal generates these four bytes of assembly:

7F 02 03 01
\$\endgroup\$
3
\$\begingroup\$

Scheme

This is the most inefficient solution I know of.

(letrec ([even? (lambda (n)
                 (if (zero? n) "even"
                     (odd? (- n 2))))]
         [odd? (lambda (n)
                 (if (= n 1) "odd"
                     (even? (- n 2))))])
  (even? (read)))
\$\endgroup\$
3
\$\begingroup\$

Perl

What about

use Math::Trig;
print(cos(pi*@ARGV[0])>0?"even":"odd")
\$\endgroup\$
2
\$\begingroup\$

JavaScript, 36

function(i){while(i>0)i-=2;return!i}

Returns true if even, false if not.

\$\endgroup\$
0
2
\$\begingroup\$

Perl

$n x '0' =~ /^(00)*$/
\$\endgroup\$
2
\$\begingroup\$

Python

zip((False, True)*(i*i), range(i*i))[-1][0]

testing the square of i, so it works for negative numbers too

\$\endgroup\$
2
\$\begingroup\$

F#

Mutual recursion for the win.

A number n is even if it is zero or (n-1) is odd.

A number n is odd if it is unequal to zero and (n-1) is even.

(abs added in case anyone's interested in the parity of negative numbers)

let rec even n = n = 0 || odd (abs n - 1) 
    and odd n = n <> 0 && even (abs n - 1)
\$\endgroup\$
2
\$\begingroup\$

Clojure

  (defmacro even?[n]
  `(= 1 ~(concat (list *) (repeat n -1))))
\$\endgroup\$
2
\$\begingroup\$

What qualifies as bitwise operations? Under the hood, integer division by 2 is likely to be implemented as a bit-shift.

Assuming bitshifts aren't out:

C/C++

(unsigned char)((unsigned char)(n > 0 ? n : -n) << 7) > 0 ? "odd" : "even"

edit Missed some parentheses, and ultimately changed to remove a shift to make it do less. You can test this with the following (in *nix):

echo 'main(){ std::cout<< (unsigned char)((unsigned char)(n > 0 ? n : -n) << 7) > 0 \
        ? "odd\n" : "even\n";}' \
  | gcc --include iostream -x c++ -o blah -
./blah

... though in Linux/tcsh, I had to escape the backslash on \n even though it was in single-quotes. I tested in little & big-endian, it works correctly in both. Also, I hand-copied this; the computer I'm posting with doesn't have a compiler, so it may have mistakes.

x86 asm

            mov eax, n          # Get the value
            cmp eax,0           # Is it zero?
            jge pos_label       # If >= 0, skip the next part
            neg eax
pos_label:

.

            imul al, 128

or

            shl  al, 7

or

            lea  eax, [eax*8]    # Multiply by 2^3 (left-shift by 3 bits)
            lea  eax, [eax*8]    # ... now it's n*2^6
            lea  eax, [eax*2]    # ... 2^7, or left-shift by 7 bits

... followed by:

            cmp al,  0          # Check whether the low byte in the low word is zero or not
            jz  even_label      # If it's zero, then it was an even number
            odd_label           # ... otherwise it wasn't

Alternatively, the shift & compare stuff could be done this way as well:

            sar al,1            # signed integer division by 2 on least-significant byte
            jc  odd_label       # jump if carry flag is set
\$\endgroup\$
1
  • \$\begingroup\$ BTW, shl and friends are disallowed... \$\endgroup\$
    – FUZxxl
    Jan 8, 2012 at 16:03
2
\$\begingroup\$

On a 68000 processor you could move a word value from the address defined by the value to test:

 move.l <number to test>,a0
 move.w (a0),d0
 ; it's even if the next instruction is executed

and let the hardware trap for address error determine the odd/even nature of the value - if the exception is raised, the value was odd, if not, the value was even:

 <set up address error trap handler>
 move.l <pointer to even string>,d1
 move.l <number to test>,a0
 move.w (a0),d0
 <reset address error trap handler>
 <print string at d1>
 <end>

 address_error_trap_handler:
 move.l <pointer to odd string>,d1
 rte

Doesn't work on Intel x86 CPUs as those are more flexible about data access.

\$\endgroup\$
2
\$\begingroup\$

Python

I decided to try for the ugliest, most confusing solution I could think of:

n=input();r=range(n+1)
print [j for i in zip(map(lambda x:str(bool(x))[4],[8&7for i in r]),
map(lambda x:str(x)[1],[[].sort()for x in r])) for j in i][n]

Prints e if even, o if odd.

\$\endgroup\$
2
\$\begingroup\$

Q

Keep subtracting 2 until x<2 then convert to bool

{1b$-[;2]/[2<=;abs x]}
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.