# Programming-Idioms

This language bar is your friend. Select your favorite languages!
Select your favorite languages :
• Or search :

# Idiom #265 Calculate parity of an integer

Set the integer variable i to 42 and calculate its parity (i.e. 0 if it contains an even number of bits, 1 if it contains an odd number of bits).

```var i = 42;
var parity = i.bitLength.isEven ? 0 : 1;
```
```parity(Number) -> parity(Number, 0).

parity(Number, Count) when Number band 1 == 1 ->
parity(Number bsr 1, Count + 1);
parity(Number, Count) when Number > 0 ->
parity(Number bsr 1, Count);
parity(_, Count) ->
Count rem 2.```
```  i = 42
print *,poppar(i)```
```let i = 42
i.toString(2)
.split('')
.reduce((parity, bit) => parity ^ bit, 0)
```
```int i = 42;
System.out.println(Integer.bitCount(i) % 2);```
```function Parity(n: Integer): Integer;
var
Mask, I, Bits: Integer;
begin
Bits := 0;
for I := 0 to SizeOf(Integer)*8 - 1 do
begin
Mask := 1 shl I;
if ((n and Mask) <> 0) then Inc(Bits);
end;
Result := Ord(Odd(Bits));
end;

begin
writeln(Parity(42));
end.```
```i := 42;
writeln(1);```
```function Parity(n: Int32): Integer;
begin
Result := Ord(Odd(PopCnt(DWORD(n))));
end;

var
i: Int32;
begin
i := 42;
writeln('Parity(42) = ',Parity(i));
end.```
```i = 42
p = bin(i).count('1') % 2```
```i = 42
i.digits(2).count(1)[0]```
```let i = 42i32;
let p = i.count_ones() % 2;```
```(define (popcount x)
(let loop ([s x]
[count 0])
(cond [(zero? s) count]
[(odd? s) (loop (arithmetic-shift s -1) (add1 count))]
[else (loop (arithmetic-shift s -1) count)])))

(define i 42)
(popcount i)```

tkoenig