[Question]
  [
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
 
 
---
**Want to improve this question?** [Update the question](/posts/2303/edit) so it's [on-topic](/help/on-topic) for Code Golf Stack Exchange.
Closed 10 years ago.
[Improve this question](/posts/2303/edit) 
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.
  
[Answer]
## Python
```
print('even' if (-1)**n==1 else 'odd')
```
[Answer]
In most programming languages division returns quotient for integers. So you can simply check this
```
(i/2)*2==i
```
[Answer]
## 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.
```
[Answer]
## Mathematica
```
SawtoothWave[x / 2] == 0
Exp[I Pi x] - 1 == 0
Sin[5 x / Pi] == 0
```
[Answer]
## 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;
}
```
[Answer]
## 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.)
[Answer]
**Python** (Slow)
```
n=1234
while n > 1: n -= 2 #slow way of modulus.
print "eovdedn"[n::2]
```
[Answer]
## 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"
```
[Answer]
## 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
```
[Answer]
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;
}
```
[Answer]
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*(‌*n*3).
---
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.
[Answer]
## 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.
```
[Answer]
## 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.
[Answer]
## Ruby
```
n.odd?
```
If you want to print out the result:
```
f[n] = ->(n){puts n.odd?? 'odd' : 'even'}
```
[Answer]
## 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
```
[Answer]
## Golfscript
```
~,2/),1=\;
```
[Answer]
## 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.
[Answer]
### 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`.
[Answer]
## 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
```
[Answer]
# 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)))
```
[Answer]
## Perl
What about
```
use Math::Trig;
print(cos(pi*@ARGV[0])>0?"even":"odd")
```
[Answer]
## JavaScript, 36
```
function(i){while(i>0)i-=2;return!i}
```
Returns `true` if even, `false` if not.
[Answer]
## Perl
```
$n x '0' =~ /^(00)*$/
```
[Answer]
## Python
```
zip((False, True)*(i*i), range(i*i))[-1][0]
```
testing the square of i, so it works for negative numbers too
[Answer]
# 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)
```
[Answer]
# Clojure
```
  (defmacro even?[n]
  `(= 1 ~(concat (list *) (repeat n -1))))
```
[Answer]
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
```
[Answer]
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.
[Answer]
# 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.
[Answer]
# Q
Keep subtracting 2 until x<2 then convert to bool
```
{1b$-[;2]/[2<=;abs x]}
```
]