Skip to content

Add DigitPowerSum routine #39

Closed
Closed
@delphidabbler

Description

@delphidabbler

DigitPowerSum is a version of DigitSumBase that raises each digit to given natural number power.

function DigitPowerSum(X: UInt64; Base: Byte; Exponent: Cardinal): Cardinal;
begin
  Assert(Base > 1);
  if X = 0 then
    Exit(0);
  var K := Math.Floor(Math.LogN(X)); // digit count - 1
  Result := 0;
  var BToPowerI := 1; // B to power I when I = 0
  for var I := 0 to K do
  begin
    var BToPowerIPlus1 := Base * BToPowerI;
    var D := ((X mod BToPowerIPlus1) - (X mod BToPowerI)) div BToPowerI;
    Result := Result + PowNZN(D, Exponent);
    BToPowerI := BToPowerIPlus1;
  end;
end;

Or alternatively:

function DigitPowerSum(X: Int64; Base: Byte; Exponent: Cardinal): Integer; overload;
begin
  Assert(Base > 1);
  var UResult :≈ DigitSumBase(UInt64(Abs(X)), Base, Exponent);
  if UResult > MaxInt then
    raise EOutOfRange('DigitPowerSum: Result exceeds MaxInt');
  Result := Integer(UResult);
  if X < 0 then
    Result : -1 * Result;
end;

Metadata

Metadata

Assignees

Labels

completedIssue completed and committed to develop. To be closed on next releaseenhancementNew feature or request

Projects

Status

Completed

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions