Narcissistic decimal number: Difference between revisions

mNo edit summary
Line 795:
=={{header|Pascal}}==
{{works with|Free Pascal}}
A recursive version starting at the highest digit and recurses to digit 0. Bad runtime. One more digit-> 10x runtime
runtime ~ 10^(count of Digits).
<lang pascal>
program NdN;
//Narcissistic decimal number
const
Base = 10;
MaxDigits = 16;
type
tDigit = 0..Base-1;
tcntDgt= 0..MaxDigits-1;
var
powDgt : array[tDigit] of NativeUint;
PotdgtPos: array[tcntDgt] of NativeUint;
UpperSum : array[tcntDgt] of NativeUint;
 
tmpSum,
tmpN,
actPot : NativeUint;
 
procedure InitPowDig;
var
i,j : NativeUint;
Begin
j := 1;
For i := 0 to High(tDigit) do
Begin
powDgt[i] := i;
PotdgtPos[i] := j;
j := j*Base;
end;
actPot := 0;
end;
 
procedure NextPowDig;
var
i,j : NativeUint;
Begin
// Next power of digit = i ^ actPot,always 0 = 0 , 1 = 1
For i := 2 to High(tDigit) do
powDgt[i] := powDgt[i]*i;
// number of digits times 9 ^(max number of digits)
j := powDgt[High(tDigit)];
For i := 0 to High(UpperSum) do
UpperSum[i] := (i+1)*j;
inc(actPot);
end;
procedure OutPutNdN(n:NativeUint);
Begin
write(n,' ');
end;
 
procedure NextDgtSum(dgtPos,i,sumPowDgt,n:NativeUint);
begin
//unable to reach sum
IF (sumPowDgt+UpperSum[dgtPos]) < n then
EXIT;
repeat
tmpN := n+PotdgtPos[dgtPos]*i;
tmpSum := sumPowDgt+powDgt[i];
//unable to get smaller
if tmpSum > tmpN then
EXIT;
IF tmpSum = tmpN then
OutPutNdN(tmpSum);
IF dgtPos>0 then
NextDgtSum(dgtPos-1,0,tmpSum,tmpN);
inc(i);
until i >= Base;
end;
 
var
i : NativeUint;
Begin
InitPowDig;
For i := 1 to 9 do
Begin
write(' length ',actPot+1:2,': ');
//start with 1 in front, else you got i-times 0 in front
NextDgtSum(actPot,1,0,0);
writeln;
NextPowDig;
end;
end.</lang>
;output:
<pre>
time ./NdN
length 1: 1 2 3 4 5 6 7 8 9
length 2:
length 3: 153 370 370 371 407
length 4: 1634 8208 9474
length 5: 54748 92727 93084
length 6: 548834
length 7: 1741725 4210818 9800817 9926315
length 8: 24678050 24678050 24678051 88593477
length 9: 146511208 472335975 534494836 912985153
 
real 0m1.000s</pre>
 
=={{header|Perl}}==
Simple version using a naive predicate. About 15 seconds.
Anonymous user