Skip to content

Commit 17fced2

Browse files
committed
Add overflow checking to PowNZN function
Updated PowNZN function in Mathematics category to check for integer overflow and to raise an EOverflow exception when detected. This change was required to trap errors when implementing DigitPowerSum, which will call PowNZN. Updated maths.ini re requirement for SysUtils unit in PowNZN and to updated description to reference the newly added exception.
1 parent cfadac8 commit 17fced2

File tree

2 files changed

+15
-4
lines changed

2 files changed

+15
-4
lines changed

collection/634.dat

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,22 @@
11
function PowNZN(const X: Integer; const N: Cardinal): Int64;
22
var
33
I: Integer;
4+
OverflowGuard: Int64;
45
begin
5-
if (X = 0) and (N > 0) then
6-
Exit(0);
7-
if X = 1 then
6+
if N = 0 then
7+
// IEEE: pown(x, 0) is 1, even when X is zero
88
Exit(1);
9+
if X = 0 then
10+
// pown(0, n) = 0, for all positive n
11+
Exit(0);
12+
OverflowGuard := High(Int64) div Abs(X);
913
Result := 1;
1014
for I := 1 to N do
15+
begin
16+
if OverflowGuard < Abs(Result) then
17+
raise SysUtils.EOverflow.CreateFmt(
18+
'Overflow calculating %d to the power %d', [X, N]
19+
);
1120
Result := Result * X;
21+
end;
1222
end;

collection/maths.ini

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1391,8 +1391,9 @@ Delphi11A=Y
13911391
Delphi12A=Y
13921392

13931393
[PowNZN]
1394-
DescEx="<p>Raises integer <var>X</var> to non-negative integer power <var>N</var>.</p>"
1394+
DescEx="<p>Raises integer <var>X</var> to non-negative integer power <var>N</var>.</p><p>If the result is too large to be represented as an <var>Int64</var> value then an <var>EOverflow</var> exception is raised.</p>"
13951395
Extra="<p>Returns an <var>integer</var> value because the power <var>N</var> is non-negative which guarantees that the result is integral.</p><p>Based on IEEE standard 754-2008 for Floating-Point Arithmetic, page 44, but which restricts <var>X</var> to an integer and <var>N</var> to a non-negative integer.</p>"
1396+
Units=SysUtils
13961397
SeeAlso=Pow,PowN,PowNZZ
13971398
TestInfo=advanced
13981399
AdvancedTest.Level=unit-tests

0 commit comments

Comments
 (0)