Odd: what changed
Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.
Title: Odd
| Old | New | Line | |
|---|---|---|---|
| 1 | + | The [[Basic Pascal Tutorial/Chapter 1/Standard Functions|standard function]] [**`odd`**](https://www.freepascal.org/docs-html/rtl/system/odd.html) returns [[True|true]] if and only if the passed [[Integer|integer]] parameter is odd, that means it is not divisible by `2`. `Odd(x)` is by definition equivalent to the [[expression]] | |
| 2 | + | ||
| 3 | + | ``` pascal | |
| 4 | + | abs(x) mod 2 = 1 | |
| 5 | + | ``` | |
| 6 | + | ||
| 7 | + | <small> The `abs` serves the purpose of any potential for confusion regarding the sign of the [[Mod|mod operator]] in conjunction with a *negative* operand. It is *unnecessary* in a *fully-ISO‑compliant* compiler (for [[FPC]] this means [[modeswitch|{$modeSwitch ISOMod+}]]). </small> | |
| 8 | + | ||
| 9 | + | ## application | |
| 10 | + | ||
| 11 | + | Beside using `odd` directly, in combination with [[Ord|ord]] it can be useful to simplify calculations. The following [[Program|program]] calculates $`1 \cdot 3^1 + 2 \cdot 3^0 + 3 \cdot 3^1 + 4 \cdot 3^0`$ (= $`3 + 2 + 9 + 4`$) without the need of [[Branch|branches]]: | |
| 12 | + | ||
| 13 | + | ``` pascal | |
| 14 | + | {$mode extendedPascal} | |
| 15 | + | program oddDemo(output); | |
| 16 | + | var | |
| 17 | + | i, sum: integer value 0; | |
| 18 | + | begin | |
| 19 | + | for i := 1 to 4 do | |
| 20 | + | begin | |
| 21 | + | { alternating scale factor 3^0, 3^1 based on Boolean } | |
| 22 | + | sum := sum + i * 3 pow ord(odd(i)); | |
| 23 | + | end; | |
| 24 | + | writeLn(sum); | |
| 25 | + | end. | |
| 26 | + | ``` | |
| 27 | + | ||
| 28 | + | <small> NB: Despite [[Mode extendedpascal|{$mode extendedPascal}]] the shown `integer` power operator `pow` and initial-value specification are not yet supported by FPC as of version 3.2.0. </small> | |
| 29 | + | ||
| 30 | + | ## notes | |
| 31 | + | ||
| 32 | + | - There is no standard built‑in function “`even`”. Obviously the expression [[Not|not odd(x)]] determines whether an `integer` is even. | |
| 33 | + | - For constant expressions, `odd` can be evaluated at compile-time, thus it can appear in the [[Const|const section]]. | |
| 34 | + | - On most architectures `odd` can be implemented as a simple `and x, 1`, that is by masking the least-significant bit in a value. For *these* platforms, using [[Type Helper|type helpers]] from the [[sysutils|sysUtils unit]], `x.testBit(0)` has the same return value. | |
| 35 | + | ||
| 36 | + | --- | |
| 37 | + | *From the Free Pascal wiki, page "Odd", as it stood on 2023-01-25 after a change by Kai Burghardt, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).* |
