Sign in Join
Wiki copytemporary

Odd

Deutsch · English · Polski

The standard function odd returns true if and only if the passed integer parameter is odd, that means it is not divisible by 2. Odd(x) is by definition equivalent to the expression

pascal
abs(x) mod 2 = 1

The abs serves the purpose of any potential for confusion regarding the sign of the mod operator in conjunction with a negative operand. It is unnecessary in a fully-ISO‑compliant compiler (for FPC this means {$modeSwitch ISOMod+}).

application

Beside using odd directly, in combination with ord it can be useful to simplify calculations. The following 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 branches:

pascal
{$mode extendedPascal}
program oddDemo(output);
var
    i, sum: integer value 0;
begin
    for i := 1 to 4 do
    begin
        { alternating scale factor 3^0, 3^1 based on Boolean }
        sum := sum + i * 3 pow ord(odd(i));
    end;
    writeLn(sum);
end.

NB: Despite {$mode extendedPascal} the shown integer power operator pow and initial-value specification are not yet supported by FPC as of version 3.2.0.

notes


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.

Revision 2, last changed by WikiArchive .

Talk about this page

Nobody has opened a bench for this page yet. Sign in to open one.