# 如何确定数字是否为奇数或偶数而无模或按位运算？[关闭]

19

3

2

dmckee

40

``````(i/2)*2==i
``````

6

Joey

1

warren

@warren取决于编程语言/编译器优化/等。此外，您可以使用`floor()`。在C和C ++中可以完美地工作。
Mateen Ulhaq

1
0是偶数吗？

4
@userunknown：是的，零为偶数。

71

## 蟒蛇

``````print('even' if (-1)**n==1 else 'odd')
``````

10

2011年

Mateen Ulhaq

21

## Brainf ***（179）

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

``````+[>,]                                                   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.
``````

21

## Mathematica

``````SawtoothWave[x / 2] == 0
Exp[I Pi x] - 1 == 0
Sin[5 x / Pi] == 0
``````

2

FUZxxl 2011年

15

## C

``````#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;
}
``````

``````int isOdd(long long input){
int a;
for(a=6;a;a--){
input*=input;
}
return !!input;
}
``````

13

Python（慢）

``````n=1234
while n > 1: n -= 2 #slow way of modulus.
print "eovdedn"[n::2]
``````

1

st0le 2011年

@Josh：这个技巧现在已经在这里出现过几次了：）
Joey

st0le 2011年

@Joey：我不认为它是新的，但是风格不必是原始的。:)
jscs 2011年

12

## 的JavaScript

``````/\$/.test(i)
``````

2

Ry- 2011年

`/-?^\d*\$/`比您的正则表达式要严格一点。您将需要更多的工作才能使其正确使用科学记数法对toString进行编号。
Thomas Eding

12

## 蟒蛇

``````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) == 2 else "Odd"
``````

``````import itertools
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"
``````

Joey

2

March Ho'7

jscs

10

## 哈斯克尔

``````odd
``````

``````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
``````

2

1

1

Thomas Eding

7

``````bool is_odd_or_even(int n)
{
return true;
}
``````

6

## 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]);
}
``````

## 哈斯克尔

``````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
``````

5

## Windows PowerShell

``````function OddOrEven([long]\$n) {
if (0,2,4,6,8 -contains "\$n"[-1]-48) {
"Even"
} else {
"Odd"
}
}
``````
1. 转换为字符串
2. 选择最后一个字母（数字）（本质上是mod 10）。
3. 检查它是0、2、4、6还是8。

5

## 辅酶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.
``````

``````Fixpoint even n:=match n with O=>true|S n=>negb(even n)end.
``````

4

## 红宝石

``````n.odd?
``````

``````f[n] = ->(n){puts n.odd?? 'odd' : 'even'}
``````

MrZander 2013年

4

## Unlambda

``````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
``````

`````````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
``````

3

## 高尔夫脚本

``````~,2/),1=\;
``````

3

## 蟒蛇

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

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

3

@jloy：噢，胡扯。我以为那是“功能而不是错误”。更多修订...
jscs 2011年

3

### Fractran

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

``````63*2^abs(n)
``````

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

`2`奇数`n``1`偶数`n`

3

## MMIX（4字节）

``````ZSEV \$2,\$3,1
``````

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

``````7F 02 03 01
``````

3

# 方案

``````(letrec ([even? (lambda (n)
(if (zero? n) "even"
(odd? (- n 2))))]
[odd? (lambda (n)
(if (= n 1) "odd"
(even? (- n 2))))])
``````

3

## 佩尔

``````use Math::Trig;
print(cos(pi*@ARGV)>0?"even":"odd")
``````

2

## JavaScript，36

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

2

## 佩尔

``````\$n x '0' =~ /^(00)*\$/
``````

2

## 蟒蛇

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

2

# F＃

（如果有人对负数的均价感兴趣，则添加abs）

``````let rec even n = n = 0 || odd (abs n - 1)
and odd n = n <> 0 && even (abs n - 1)
``````

2

# C / C ++

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

``````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
``````

...尽管在Linux / tcsh中，我不得不在 `\n`即使在单引号中。我在little＆big-endian中进行了测试，在两者中均正常工作。另外，我手工复制了这个。我要发布的计算机没有编译器，因此可能有错误。

# x86汇编

``````            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
``````

``````            shl  al, 7
``````

``````            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
``````

... 其次是：

``````            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
``````

``````            sar al,1            # signed integer division by 2 on least-significant byte
jc  odd_label       # jump if carry flag is set
``````

FUZxxl 2012年

2

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

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

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

2

# 蟒蛇

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

2

# 问

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