Even or odd: Difference between revisions
(→{{header|Groovy}}: new solution) |
|||
Line 370: | Line 370: | ||
# The next way only works when n.to_f/2 is exact. |
# The next way only works when n.to_f/2 is exact. |
||
# If Float is IEEE double, then -2**53 .. 2**53 must include n. |
# If Float is IEEE double, then -2**53 .. 2**53 must include n. |
||
n.to_f/2 == n/2 |
n.to_f/2 == n/2 |
||
# You can use the bracket operator to access the i'th bit |
|||
# of a Fixnum or Bignum (i = 0 means least significant bit) |
|||
n[0].zero?</lang> |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
Revision as of 07:16, 21 December 2011
You are encouraged to solve this task according to the task description, using any language you may know.
Test whether an integer is even or odd.
There is more than one way to solve this task:
- Use the even and odd predicates, if the language provides them.
- Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
- Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd.
- Use modular congruences:
- i ≡ 0 (mod 2) iff i is even.
- i ≡ 1 (mod 2) iff i is odd.
AutoHotkey
Bitwise ops are probably most efficient: <lang AHK>if ( int & 1 ){ ; do odd stuff }else{ ; do even stuff }</lang>
bc
There are no bitwise operations, so this solution compares a remainder with zero. Calculation of i % 2 only works when scale = 0.
<lang bc>i = -3
/* Assumes that i is an integer. */ scale = 0 if (i % 2 == 0) "i is even " if (i % 2) "i is odd "</lang>
C
Test by bitwise and'ing 1, works for any builtin integer type as long as it's 2's compliment (it's always so nowadays): <lang c>if (x & 1) {
/* x is odd */
} else {
/* or not */
}</lang>
If using long integer type from GMP (mpz_t
), there are provided macros:
<lang c>mpz_t x;
...
if (mpz_even_p(x)) { /* x is even */ }
if (mpz_odd_p(x)) { /* x is odd */ }</lang>
The macros evaluate x
more than once, so it should not be something with side effects.
C#
<lang csharp>namespace RosettaCode {
using System;
public static class EvenOrOdd { public static bool IsEvenBitwise(this int number) { return (number & 1) == 0; }
public static bool IsOddBitwise(this int number) { return (number & 1) != 0; }
public static bool IsEvenRemainder(this int number) { int remainder; Math.DivRem(number, 2, out remainder); return remainder == 0; }
public static bool IsOddRemainder(this int number) { int remainder; Math.DivRem(number, 2, out remainder); return remainder != 0; }
public static bool IsEvenModulo(this int number) { return (number % 2) == 0; }
public static bool IsOddModulo(this int number) { return (number % 2) != 0; } }
}</lang>
Common Lisp
Standard predicates: <lang lisp>(if (evenp some-var) (do-even-stuff)) (if (oddp some-other-var) (do-odd-stuff))</lang>
DWScript
Predicate: <lang delphi>var isOdd := Odd(i);</lang> Bitwise and: <lang delphi>var isOdd := (i and 1)<>0;</lang> Modulo: <lang delphi>var isOdd := (i mod 2)=1;</lang>
Factor
The math vocabulary provides even? and odd? predicates. This example runs at the listener, which already uses the math vocabulary.
( scratchpad ) 20 even? . t ( scratchpad ) 35 even? . f ( scratchpad ) 20 odd? . f ( scratchpad ) 35 odd? . t
Forth
<lang forth>: odd? ( n -- ? ) 1 and ;</lang>
Go
<lang go>package main
import (
"fmt" "math/big"
)
func main() {
test(-2) test(-1) test(0) test(1) test(2) testBig("-222222222222222222222222222222222222") testBig("-1") testBig("0") testBig("1") testBig("222222222222222222222222222222222222")
}
func test(n int) {
fmt.Printf("Testing integer %3d: ", n) // & 1 is a good way to test if n&1 == 0 { fmt.Print("even ") } else { fmt.Print(" odd ") } // Careful when using %: negative n % 2 returns -1. So, the code below // works, but can be broken by someone thinking they can reverse the // test by testing n % 2 == 1. The valid reverse test is n % 2 != 0. if n%2 == 0 { fmt.Println("even") } else { fmt.Println(" odd") }
}
func testBig(s string) {
b, _ := new(big.Int).SetString(s, 10) fmt.Printf("Testing big integer %v: ", b) // the Bit function is the only sensible test for big ints. if b.Bit(0) == 0 { fmt.Println("even") } else { fmt.Println("odd") }
}</lang> Output:
Testing integer -2: even even Testing integer -1: odd odd Testing integer 0: even even Testing integer 1: odd odd Testing integer 2: even even Testing big integer -222222222222222222222222222222222222: even Testing big integer -1: odd Testing big integer 0: even Testing big integer 1: odd Testing big integer 222222222222222222222222222222222222: even
Groovy
Solution: <lang groovy>def isOdd = { int i -> (i & 1) as boolean } def isEven = {int i -> ! isOdd(i) }</lang>
Test: <lang groovy>1.step(20, 2) { assert isOdd(it) }
50.step(-50, -2) { assert isEven(it) }</lang>
Haskell
even
and odd
functions are already included in the standard Prelude.
<lang haskell>Prelude> even 5 False Prelude> even 42 True Prelude> odd 5 True Prelude> odd 42 False</lang>
Icon and Unicon
One way is to check the remainder: <lang unicon>procedure isEven(n)
return n%2 = 0
end</lang>
J
Modulo:
<lang j> 2 | 2 3 5 7 0 1 1 1
2|2 3 5 7 + (2^89x)-1
1 0 0 0</lang>
Remainder:
<lang j> (= <.&.-:) 2 3 5 7 1 0 0 0
(= <.&.-:) 2 3 5 7+(2^89x)-1
0 1 1 1</lang>
Last bit in bit representation: <lang j> {:"1@#: 2 3 5 7 0 1 1 1
{:"1@#: 2 3 5 7+(2^89x)-1
1 0 0 0</lang>
Bitwise and:
<lang j> 1 (17 b.) 2 3 5 7 0 1 1 1</lang>
Note: as a general rule, the simplest expressions in J should be preferred over more complex approaches.
Java
Bitwise and: <lang java>public static boolean isEven(int i){
return (i & 1) == 0;
}</lang> Modulo: <lang java>public static boolean isEven(int i){
return (i % 2) == 0;
}</lang> Arbitrary precision bitwise: <lang java>public static boolean isEven(BigInteger i){
return i.and(BigInteger.ONE).equals(BigInteger.ZERO);
}</lang>
Arbitrary precision bit test (even works for negative numbers because of the way BigInteger
represents the bits of numbers):
<lang java>public static boolean isEven(BigInteger i){
return !i.testBit(0);
}</lang> Arbitrary precision modulo: <lang java>public static boolean isEven(BigInteger i){
return i.mod(BigInteger.valueOf(2)).equals(BigInteger.ZERO);
}</lang>
Mathematica
<lang Mathematica>EvenQ[8]</lang>
Mercury
Mercury's 'int' module provides tests for even/odd, along with all the operators that would be otherwise used to implement them.
<lang Mercury>even(N) % in a body, suceeeds iff N is even. odd(N). % in a body, succeeds iff N is odd.
% rolling our own:
- - pred even(int::in) is semidet.
% It's an error to have all three in one module, mind; even/1 would fail to check as semidet. even(N) :- N mod 2 = 0. % using division that truncates towards -infinity even(N) :- N rem 2 = 0. % using division that truncates towards zero even(N) :- N /\ 1 = 0. % using bit-wise and.</lang>
OCaml
Modulo:
<lang ocaml>let is_even d =
(d mod 2) = 0
let is_odd d =
(d mod 2) <> 0</lang>
Bitwise and:
<lang ocaml>let is_even d =
(d land 1) = 0
let is_odd d =
(d land 1) <> 0</lang>
PARI/GP
GP does not have a built-in predicate for testing parity, but it's easy to code: <lang parigp>odd(n)=n%2;</lang> Alternately: <lang parigp>odd(n)=bitand(n,1);</lang>
PARI can use the same method as C for testing individual words. For multiprecision integers (t_INT), use mpodd
. If the number is known to be nonzero, mod2
is (insignificantly) faster.
Perl
<lang perl>for(0..10){
print "$_ is ", qw(even odd)[$_ % 2],"\n";
}</lang> or <lang perl>print 6 % 2 ? 'odd' : 'even'; # prints even</lang>
Perl 6
Perl 6 doesn't have a built-in for this, but with subsets it's easy to define a predicate for it. <lang perl6>subset Even of Int where * %% 2; subset Odd of Int where * % 2;
say 1 ~~ Even; # false say 1 ~~ Odd; # true say 1.5 ~~ Odd # false ( 1.5 is not an Int )</lang>
PicoLisp
PicoLisp doesn't have a built-in predicate for that. Using 'bit?' is the easiest and most efficient. The bit test with 1 will return NIL if the number is even. <lang PicoLisp>: (bit? 1 3) -> 1 # Odd
- (bit? 1 4)
-> NIL # Even</lang>
Pike
<lang Pike>> int i = 73; > (i&1); Result: 1 > i%2; Result: 1</lang>
PureBasic
<lang PureBasic>;use last bit method isOdd = i & 1 ;isOdd is non-zero if i is odd isEven = i & 1 ! 1 ;isEven is non-zero if i is even
- use modular method
isOdd = i % 2 ;isOdd is non-zero if i is odd isEven = i % 2 ! 1 ;isEven is non-zero if i is even</lang>
Python
<lang python>>>> def is_odd(i): return bool(i & 1)
>>> def is_even(i): return not is_odd(i)
>>> [(j, is_odd(j)) for j in range(10)] [(0, False), (1, True), (2, False), (3, True), (4, False), (5, True), (6, False), (7, True), (8, False), (9, True)] >>> [(j, is_even(j)) for j in range(10)] [(0, True), (1, False), (2, True), (3, False), (4, True), (5, False), (6, True), (7, False), (8, True), (9, False)] >>> </lang>
Ruby
Ruby 1.8.7 added Integer#even? and Integer#odd? as new methods.
<lang ruby>print "evens: " p -5.upto(5).select {|n| n.even?} print "odds: " p -5.upto(5).select {|n| n.odd?}</lang>
outputs
evens: [-4, -2, 0, 2, 4] odds: [-5, -3, -1, 1, 3, 5]
Other ways to test even-ness: <lang ruby>n & 1 == 0 quotient, remainder = n.divmod(2); remainder == 0
- The next way only works when n.to_f/2 is exact.
- If Float is IEEE double, then -2**53 .. 2**53 must include n.
n.to_f/2 == n/2
- You can use the bracket operator to access the i'th bit
- of a Fixnum or Bignum (i = 0 means least significant bit)
n[0].zero?</lang>
Tcl
<lang tcl>package require Tcl 8.5
- Bitwise test is the most efficient
proc tcl::mathfunc::isOdd x { expr {$x & 1} } proc tcl::mathfunc::isEven x { expr {!($x & 1)} }
puts " # O E" puts 24:[expr isOdd(24)],[expr isEven(24)] puts 49:[expr isOdd(49)],[expr isEven(49)]</lang> Output:
# O E 24:0,1 49:1,0
TUSCRIPT
<lang tuscript> $$ MODE TUSCRIPT LOOP n=-5,5 x=MOD(n,2) SELECT x CASE 0 PRINT n," is even" DEFAULT PRINT n," is odd" ENDSELECT ENDLOOP </lang> Output:
-5 is odd -4 is even -3 is odd -2 is even -1 is odd 0 is even 1 is odd 2 is even 3 is odd 4 is even 5 is odd