Skip to content

Commit ca2c9c2

Browse files
✨ feat(Integer): Add parity testing methods.
1 parent bbf7ee6 commit ca2c9c2

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

src/Integer.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -370,6 +370,20 @@ export class Integer {
370370
return !this.iszero();
371371
}
372372

373+
parity ( ) {
374+
// TODO optimize this, there is a much faster way to test for parity
375+
// when the base is a multiple of two
376+
return this.modn(2) ;
377+
}
378+
379+
iseven ( ) {
380+
return this.parity().iszero() ;
381+
}
382+
383+
isodd ( ) {
384+
return !this.iseven() ;
385+
}
386+
373387
bin ( ) {
374388
return this.toString( 2 ) ;
375389
}

test/src/Integer/parity.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import test from 'ava' ;
2+
import { range } from '@aureooms/js-itertools' ;
3+
4+
import { ZZ } from '../../../src' ;
5+
6+
function even ( t , x ) {
7+
t.true(x.iseven());
8+
t.false(x.isodd());
9+
}
10+
11+
even.title = ( providedTitle , x ) => `parity: ${x.toString()} is even` ;
12+
13+
function odd ( t , x ) {
14+
t.true(x.isodd());
15+
t.false(x.iseven());
16+
}
17+
18+
odd.title = ( providedTitle , x ) => `parity: ${x.toString()} is odd` ;
19+
20+
test( odd , ZZ.from('123456789') ) ;
21+
test( odd , ZZ.from('987654321') ) ;
22+
test( even , ZZ.from('9876543210') ) ;
23+
24+
test( odd , ZZ.from('ff', 16) ) ;
25+
26+
test( even , ZZ.from(2).pow(1234) ) ;
27+
test( odd , ZZ.from(2).pow(1234).subn(1) ) ;
28+
29+
const N = 100 ;
30+
let x = ZZ.from(-N);
31+
32+
for ( const i of range(N) ) {
33+
test( even , x ) ;
34+
x = x.addn(1) ;
35+
test( odd , x ) ;
36+
x = x.addn(1) ;
37+
}

0 commit comments

Comments
 (0)