Narcissistic decimal number: Difference between revisions

→‎{{header|Perl 6}}: add a faster version
m (→‎{{header|REXX}}: changed the section names.)
(→‎{{header|Perl 6}}: add a faster version)
Line 147:
 
Here the program was interrupted but if you're patient enough you'll see all the 25 numbers.
 
Here's a faster version that precalculates the values for base 1000 digits:
<lang perl6>sub kigits($n) {
my int $i = $n;
my int $b = 1000;
my @result;
while $i { push @result, $i % $b; $i = $i div $b }
@result;
}
 
constant narcissistic = 0, map -> $d {
my @t = 0..9 X** $d;
my @table = @t X+ @t X+ @t;
sub is-narcissistic(\n) { n == [+] @table[kigits(n)] }
gather take $_ if is-narcissistic($_) for 10**($d-1) ..^ 10**$d;
}, 1..*;
 
for narcissistic {
say ++state $n, "\t", $_;
last if $n == 25;
}</lang>
{{out}}
<pre>1 0
2 1
3 2
4 3
5 4
6 5
7 6
8 7
9 8
10 9
11 153
12 370
13 371
14 407
15 1634
16 8208
17 9474
18 54748
19 92727
20 93084
21 548834
22 1741725
23 4210818
24 9800817
25 9926315</pre>
 
=={{header|Python}}==
Anonymous user