Narcissistic decimal number: Difference between revisions
Content added Content deleted
SqrtNegInf (talk | contribs) m (→{{header|Raku}}: split versions apart, add concurrency to 1st) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 32:
{{trans|Python}}
<
[Int] result
L(digits) 0..
Line 49:
print(n, end' ‘ ’)
I (L.index + 1) % 5 == 0
print()</
{{out}}
Line 62:
=={{header|Ada}}==
<
procedure Narcissistic is
Line 93:
Current := Current + 1;
end loop;
end Narcissistic;</
{{out}}
Line 100:
=={{header|Agena}}==
Tested with Agena 2.9.5 Win32
<
# print the first 25 narcissistic numbers
Line 155:
io.writeline()
epocs</
{{out}}
<pre>
Line 162:
=={{header|ALGOL 68}}==
<
# returns TRUE if n is narcissitic, FALSE otherwise; n should be >= 0 #
Line 194:
FI
OD;
print( ( newline ) )</
{{out}}
<pre>
Line 202:
=={{header|ALGOL W}}==
{{Trans|Agena}}
<
% print the first 25 narcissistic numbers %
Line 267:
write()
end.</
{{out}}
<pre>
Line 274:
=={{header|APL}}==
<
∇r ← digitsOf n;digitList
digitList ← ⍬
Line 308:
getASN 25
0 1 2 3 4 5 6 7 8 9 153 370 371 407 1634 8208 9474 54748 92727 93084 548834 1741725 4210818 9800817 9926315
</syntaxhighlight>
=={{header|AppleScript}}==
Line 322:
For an imperative hand-optimisation, and a contrasting view, see the variant approach below :-)
<
-- isDaffodil :: Int -> Int -> Bool
Line 493:
end script
end if
end mReturn</
{{Out}}
<
----
Line 502:
When corrected actually to return the 25 numbers required by the task, the JavaScript/Haskell translation above takes seven minutes fifty-three seconds on my current machine. By contrast, the code here was written from scratch in AppleScript, takes the number of results required as its parameter rather than the numbers of digits in them, and returns the 25 numbers in just under a sixth of a second. The first 41 numbers take just under four-and-a-half seconds, the first 42 twenty-seven, and the first 44 a minute thirty-seven-and-a-half. The 43rd and 44th numbers are both displayed in Script Editor's result pane as 4.33828176939137E+15, but appear to be the correct values when tested. The JavaScript/Haskell translation's problems are certainly ''not'' due to AppleScript being "a little out of its depth here", but the narcissistic decimal numbers beyond the 44th are admittedly beyond the resolution of AppleScript's number classes.
<
Return the first q narcissistic decimal numbers
(or as many of the q as can be represented by AppleScript number values).
Line 580:
end narcissisticDecimalNumbers
return narcissisticDecimalNumbers(25)</
{{output}}
<
=={{header|Arturo}}==
{{trans|REXX}}
<
map 0..9 'y [
x ^ y
Line 612:
]
inc 'i
]</
{{out}}
Line 643:
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">
#NoEnv ; Do not try to use environment variables
SetBatchLines, -1 ; Execute as quickly as you can
Line 686:
}
}
</syntaxhighlight>
{{out}}
Line 703:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f NARCISSISTIC_DECIMAL_NUMBER.AWK
BEGIN {
Line 720:
exit(0)
}
</syntaxhighlight>
<p>output:</p>
<pre>
Line 730:
This can take several minutes to complete in most interpreters, so it's probably best to use a compiler if you want to see the full sequence.
<
>1>+>^v\_^#!:<p01p00:+1<>\>
>#-_>\>20p110g>\20g*\v>1-v|
^!p00:-1g00+$_^#!:<-1<^\.:<</
{{out}}
Line 743:
<code>B10</code> is a BQNcrate idiom to get the digits of a number.
<
IsNarc ← {𝕩=+´⋆⟜≠B10 𝕩}
/IsNarc¨ ↕1e7</
A much faster method is to generate a list of digit sums as addition tables (<code>+⌜</code>). A different list of digit sums is generated for each digit count, 0 to 7. To avoid leading 0s, 0 is removed from the first digit list with <code>(0=↕)↓¨</code>. Then all that needs to be done is to join the lists and return locations where the index (number) and value (digit power sum) are equal.
<
=={{header|C}}==
Line 756:
The following prints the first 25 numbers, though not in order...
<
#include <gmp.h>
Line 818:
return 0;
}</
{{out}}
<pre>
Line 843:
=={{header|C sharp|C#}}==
<
using System;
Line 883:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 893:
</pre>
===or===
<
//Narcissistic numbers: Nigel Galloway: February 17th., 2015
using System;
Line 922:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 955:
{{libheader|System.Numerics}}
{{trans|FreeBASIC}} (FreeBASIC, GMP version)<br/>Why stop at 25? Even using '''ulong''' instead of '''int''' only gets one to the 44th item. The 89th (last) item has 39 digits, which '''BigInteger''' easily handles. Of course, the BigInteger implementation is slower than native data types. But one can compensate a bit by calculating in parallel. Not bad, it can get all 89 items in under 7 1/2 minutes on a core i7. The calculation to the 25th item takes a fraction of a second. The calculation for all items up to 25 digits long (67th item) takes about half a minute with sequential processing and less than a quarter of a minute using parallel processing. Note that parallel execution involves some overhead, and isn't a time improvement unless computing around 15 digits or more. This program can test all numbers up to 61 digits in under half an hour, of course the highest item found has only 39 digits.
<
using System.Collections.Generic;
using System.Linq;
Line 1,072:
}
}
</syntaxhighlight>
{{out}}(with command line parameter = "39")
<pre style="height:30ex;overflow:scroll">Calculations in parallel... 7 6 5 4 3 2 1 11 10 9 8 15 14 13 12 19 18 17 16 23 22 20 21 26 27 25 24 30 31 29 34 28 35 38 33 39 32 37 36
Line 1,237:
=={{header|C++}}==
<
#include <iostream>
#include <vector>
Line 1,305:
return system( "pause" );
}
</syntaxhighlight>
{{out}}
<pre>
Line 1,313:
=={{header|Clojure}}==
Find N first Narcissistic numbers.
<syntaxhighlight lang="clojure">
(ns narcissistic.core
(:require [clojure.math.numeric-tower :as math]))
Line 1,327:
(defn firstNnarc [n] ;;list of the first "n" Narcissistic numbers.
(take n (filter narcissistic? (range))))
</syntaxhighlight>
{{out}}
by Average-user
Line 1,337:
=={{header|COBOL}}==
<syntaxhighlight lang="cobol">
PROGRAM-ID. NARCISSIST-NUMS.
DATA DIVISION.
Line 1,396:
END PROGRAM NARCISSIST-NUMS.
</syntaxhighlight>
{{out}}
Line 1,425:
=={{header|Common Lisp}}==
<
(defun integer-to-list (n)
(map 'list #'digit-char-p (prin1-to-string n)))
Line 1,440:
counting (narcissisticp c) into narcissistic
do (if (narcissisticp c) (print c))))
</syntaxhighlight>
{{out}}
<pre>
Line 1,475:
=={{header|D}}==
===Simple Version===
<
import std.stdio, std.algorithm, std.conv, std.range;
Line 1,482:
writefln("%(%(%d %)\n%)",
uint.max.iota.filter!isNarcissistic.take(25).chunks(5));
}</
{{out}}
<pre>0 1 2 3 4
Line 1,492:
===Fast Version===
{{trans|Python}}
<
uint[] narcissists(in uint m) pure nothrow @safe {
Line 1,520:
void main() {
writefln("%(%(%d %)\n%)", 25.narcissists.chunks(5));
}</
With LDC2 compiler prints the same output in less than 0.3 seconds.
===Faster Version===
{{trans|C}}
<
struct Narcissistics(TNum, uint maxLen) {
Line 1,578:
foreach (immutable i; 1 .. maxLength + 1)
narc.show(i);
}</
{{out}}
<pre>length 1: 9 8 7 6 5 4 3 2 1 0
Line 1,600:
=={{header|Elixir}}==
{{trans|D}}
<
def narcissistic(m) do
Enum.reduce(1..10, [0], fn digits,acc ->
Line 1,631:
catch
x -> IO.inspect x
end</
{{out}}
Line 1,640:
=={{header|ERRE}}==
<
!$DOUBLE
Line 1,661:
N=N+1
END LOOP
END PROGRAM</
Output
<pre>
Line 1,669:
=={{header|F Sharp|F#}}==
<
//Naïve solution of Narcissitic number: Nigel Galloway - Febryary 18th., 2015
open System
Line 1,677:
let d = _Digits (n, [])
d |> List.fold (fun a l -> a + int ((float l) ** (float (List.length d)))) 0 = n) |> Seq.take(25) |> Seq.iter (printfn "%A")
</syntaxhighlight>
{{out}}
<pre>
Line 1,708:
=={{header|Factor}}==
<syntaxhighlight lang="text">USING: io kernel lists lists.lazy math math.functions
math.text.utils prettyprint sequences ;
IN: rosetta-code.narcissistic-decimal-number
Line 1,722:
: main ( -- ) first25 [ pprint bl ] each ;
MAIN: main</
{{out}}
<pre>
Line 1,730:
=={{header|Forth}}==
{{works with|GNU Forth|0.7.0}}
<
: dig.num \ returns input number and the number of its digits ( n -- n n1 )
dup
Line 1,810:
25 narc.num
</syntaxhighlight>
{{out}}
<pre>
Line 1,843:
=={{header|FreeBASIC}}==
===Simple Version===
<
' compile with: fbc -s console
' can go up to 18 digits (ulongint is 64bit), above 18 overflow will occur
Line 1,903:
Print : Print "hit any key to end program"
Sleep
End</
{{out}}
<pre>9
Line 1,934:
<pre>It takes about 35 min. to find all 88 numbers (39 digits).
To go all the way it takes about 2 hours.</pre>
<
' uses gmp
' compile with: fbc -s console
Line 2,036:
Print : Print "hit any key to end program"
Sleep
End</
{{out}}
Left side: program output, right side: sorted on length, value
Line 2,130:
=={{header|FunL}}==
<
power = 1
powers = array( 0..9 )
Line 2,149:
narc( start )
println( narcissistic(0).take(25) )</
{{out}}
Line 2,167:
=={{header|Go}}==
Nothing fancy as it runs in a fraction of a second as-is.
<
import "fmt"
Line 2,195:
func main() {
fmt.Println(narc(25))
}</
{{out}}
<pre>
Line 2,204:
{{trans|FreeBASIC}}
Maximum for N (double) is14 digits, there are no 15 digits numbers
<
2 FOR A = 0 TO 9 : X2(A) = A : NEXT A
3 FOR N = 1 TO 7
Line 2,234:
29 PRINT
30 PRINT "done"
31 END</
{{out}}
<pre> 9 8 7 6 5
Line 2,244:
=={{header|Haskell}}==
===Exhaustive search (integer series)===
<
isNarcissistic :: Int -> Bool
Line 2,253:
main :: IO ()
main = mapM_ print $ take 25 (filter isNarcissistic [0 ..])</
===Reduced search (unordered digit combinations)===
Line 2,260:
In this way we can find the 25th narcissistic number after '''length $ concatMap digitPowerSums [1 .. 7] == 19447''' tests – an improvement on the exhaustive trawl through '''9926315''' integers.
<
narcissiOfLength :: Int -> [Int]
Line 2,306:
w = maximum (length . xShow <$> xs)
in unlines $
s : fmap (((++) . rjust w ' ' . xShow) <*> ((" -> " ++) . fxShow . f)) xs</
{{Out}}
<pre>Narcissistic decimal numbers of length 1-7:
Line 2,321:
The following is a quick, dirty, and slow solution that works in both languages:
<
limit := integer(A[1]) | 25
every write(isNarcissitic(seq(0))\limit)
Line 2,331:
every (sum := 0) +:= (!sn)^m
return sum = n
end</
Sample run:
Line 2,365:
=={{header|J}}==
<
isNarc=: (= +/@(] ^ #)@getDigits)"0 NB. test numbers for Narcissism</
'''Example Usage'''
<
0 1 2 3 4 5 6 7 8 9 153 370 371 407 1634 8208 9474 54748 92727 93084 548834 1741725 4210818 9800817 9926315</
=={{header|Java}}==
{{works with|Java|1.5+}}
<
public static boolean isNarc(long x){
if(x < 0) return false;
Line 2,395:
}
}
}</
{{out}}
<pre>0 1 2 3 4 5 6 7 8 9 153 370 371 407 1634 8208 9474 54748 92727 93084 548834 1741725 4210818 9800817 9926315 </pre>
Line 2,401:
{{works with|Java|1.8}}
The statics and the System.exit(0) stem from having first developed a version that is not limited by the amount of narcisstic numbers that are to be calculated. I then read that this is a criterion and thus the implementation is an afterthought and looks awkwardish... but still... works!
<
import java.util.stream.IntStream;
public class NarcissisticNumbers {
Line 2,427:
});
}
}</
{{out}}
<pre>0 1 2 3 4 5 6 7 8 9 153 370 371 407 1634 8208 9474 54748 92727 93084 548834 1741725 4210818 9800817 9926315 </pre>
Line 2,434:
===ES5===
{{trans|Java}}
<
var str = x.toString(),
i,
Line 2,457:
}
return n.join(' ');
}</
{{out}}
<pre>"0 1 2 3 4 5 6 7 8 9 153 370 371 407 1634 8208 9474 54748 92727 93084 548834 1741725 4210818 9800817 9926315"</pre>
Line 2,463:
===ES6===
====Exhaustive search (integer series)====
<
'use strict';
Line 2,502:
)
.narc
})();</
{{Out}}
<
Line 2,514:
(Generating the unordered digit combinations directly as power sums allows faster testing later, and needs less space)
<
'use strict';
Line 2,657:
// MAIN ---
return main();
})();</
{{Out}}
<pre>Narcissistic decimal numbers of lengths [1..7]:
Line 2,674:
A function for checking whether a given non-negative integer is narcissistic could be implemented in jq as follows:
<
def digits: tostring | explode[] | [.] | implode | tonumber;
def pow(n): . as $x | reduce range(0;n) as $i (1; . * $x);
Line 2,680:
(tostring | length) as $len
| . == reduce digits as $d (0; . + ($d | pow($len)) )
end;</
In the following, this definition is modified to avoid recomputing (d ^ i). This is accomplished introducing the array [i, [0^i, 1^i, ..., 9^i]].
To update this array for increasing values of i, the function powers(j) is defined as follows:
<
# Output: [j, [0^j, 1^j, 2^j, ..., 9^j]]
# provided j is i or (i+1)
Line 2,691:
else .[0] += 1
| reduce range(0;10) as $k (.; .[1][$k] *= $k)
end;</
The function is_narcisstic can now be modified to use powers(j) as follows:
<
def is_narcissistic:
def digits: tostring | explode[] | [.] | implode | tonumber;
Line 2,701:
| if . < 0 then false
else . == reduce digits as $d (0; . + $powers[$d] )
end;</
'''The task'''
<
def while(cond; update):
def _while: if cond then ., (update | _while) else empty end;
Line 2,725:
| "\(.[2]): \(.[0])" ;
narcissistic(25)</
{{out}}
<
1: 0
2: 1
Line 2,752:
23: 4210818
24: 9800817
25: 9926315</
=={{header|Julia}}==
This easy to implement brute force technique is plenty fast enough to find the first few Narcissistic decimal numbers.
<
function isnarcissist(n, b=10)
Line 2,779:
findnarcissist()
@time findnarcissist(true)
</
<pre>
Finding the first 25 Narcissistic numbers:
Line 2,811:
=={{header|Kotlin}}==
<
fun isNarcissistic(n: Int): Boolean {
Line 2,839:
}
while (count < 25)
}</
{{out}}
Line 2,848:
=={{header|Ksh}}==
<
#!/bin/ksh
Line 2,889:
_isnarcissist ${i} ; (( $? )) && printf "%3d. %d\n" $(( ++cnt )) ${i}
done
</syntaxhighlight>
{{out}}<pre>
1. 0
Line 2,919:
=={{header|Lua}}==
This is a simple/naive/slow method but it still spits out the requisite 25 in less than a minute using LuaJIT on a 2.5 GHz machine.
<
local m, sum, digit = string.len(n), 0
for pos = 1, m do
Line 2,935:
end
n = n + 1
until count == 25</
{{out}}
<pre>
Line 2,942:
=={{header|Maple}}==
<syntaxhighlight lang="maple">
Narc:=proc(i)
Line 2,966:
end do:
NDN;
</syntaxhighlight>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
narc[n_] := narc[n] = NestWhile[# + 1 &, narc[n - 1] + 1, Plus @@ (IntegerDigits[#]^IntegerLength[#]) != # &];
narc /@ Range[25]</
{{out}}
<pre>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474, 54748, 92727, 93084, 548834, 1741725, 4210818, 9800817, 9926315}</pre>
=={{header|MATLAB}}==
<
x = 0;
c = 0;
Line 2,992:
dig = sprintf('%d', n) - '0';
tf = n == sum(dig.^length(dig));
end</
{{out}}
<pre>0 1 2 3 4 5 6 7 8 9 153 370 371 407 1634 8208 9474 54748 92727 93084 548834 1741725 4210818 9800817 9926315</pre>
=={{header|Nanoquery}}==
<
digits = {}
for digit in str(num)
Line 3,029:
print num + " "
end
println</
{{out}}
<pre>0 1 2 3 4 5 6 7 8 9 153 370 371 407 1634 8208 9474 54748 92727 93084 548834 1741725 4210818 9800817 9926315 </pre>
Line 3,035:
=={{header|Nim}}==
A simple solution which runs in about one second.
<
func digits(n: Natural): seq[int] =
Line 3,061:
m *= 10
echo findNarcissistic(25).join(" ")</
{{out}}
Line 3,068:
=={{header|Oforth}}==
<
| i m |
n 0 while( n ) [ n 10 /mod ->n swap 1 + ] ->m
Line 3,077:
ListBuffer new dup ->l
0 while(l size n <>) [ dup isNarcissistic ifTrue: [ dup l add ] 1 + ] drop ;
</syntaxhighlight>
{{out}}
Line 3,088:
=={{header|PARI/GP}}==
Naive code, could be improved by splitting the digits in half and meeting in the middle.
<
v=List();for(n=1,1e9,if(isNarcissistic(n),listput(v,n);if(#v>24, return(Vec(v)))))</
{{out}}
<pre>%1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474, 54748, 92727, 93084, 548834, 1741725, 4210818, 9800817, 9926315, 24678050]</pre>
Line 3,097:
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).
<
program NdN;
//Narcissistic decimal number
Line 3,178:
NextPowDig;
end;
end.</
;output:
<pre>
Line 3,196:
recursive solution.Just counting the different combination of digits<BR>
See [[Combinations_with_repetitions]]<BR>
<
{$IFDEF FPC}
{$MODE DELPHI}{$OPTIMIZATION ON,ALL}{$COPERATORS ON}
Line 3,398:
{$ENDIF}
end.
</syntaxhighlight>
{{out|@TIO.RUN}}
<pre style="height:180px">
Line 3,464:
=={{header|Perl}}==
Simple version using a naive predicate.
<
sub is_narcissistic ($n) {
Line 3,478:
}
say join ' ', @N;</
{{out}}
<pre>0 1 2 3 4 5 6 7 8 9 153 370 371 407 1634 8208 9474 54748 92727 93084 548834 1741725 4210818 9800817 9926315</pre>
=={{header|Phix}}==
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">narcissistic</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
Line 3,502:
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<!--</
{{out}}
<pre>
Line 3,511:
At least 100 times faster, gets the first 47 (the native precision limit) before the above gets the first 25.<br>
I tried a gmp version, but it was 20-odd times slower, presumably because it uses that mighty sledgehammer for many small int cases.
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #000080;font-style:italic;">-- Begin with zero, which is narcissistic by definition and is never the only digit used in other numbers.</span>
Line 3,587:
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"found %d in %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">)})</span>
<!--</
{{out}}
<pre>
Line 3,605:
=={{header|PicoLisp}}==
<
(loop
(when
Line 3,617:
(T (=0 C) 'done) ) )
(bye)</
=={{header|PL/I}}==
===version 1===
{{trans|REXX}}
<
Dcl (j,k,l,nn,n,sum) Dec Fixed(15)init(0);
Dcl s Char(15) Var;
Line 3,673:
Return(result);
End
End;</
{{out}}
<pre> 1 narcissistic: 0 0 16:10:17.586
Line 3,708:
===version 2===
Precompiled powers
<syntaxhighlight lang="text">*process source xref attributes or(!);
narn3: Proc Options(main);
Dcl (i,j,k,l,nn,n,sum) Dec Fixed(15)init(0);
Line 3,764:
Return(result);
End;
End;</
{{out}}
<pre> 1 narcissistic: 0 0 00:41:43.632
Line 3,798:
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
function Test-Narcissistic ([int]$Number)
{
Line 3,829:
$narcissisticNumbers | Format-Wide {"{0,7}" -f $_} -Column 5 -Force
</syntaxhighlight>
{{Out}}
<pre>
Line 3,843:
This solution pre-computes the powers once.
<
from itertools import count, islice
Line 3,860:
print(n, end=' ')
if i % 5 == 0: print()
print()</
{{out}}
Line 3,872:
{{trans|D}}
<
import psyco
psyco.full()
Line 3,929:
narc.show(i)
main()</
{{out}}
<pre>length 1: 9 8 7 6 5 4 3 2 1 0
Line 3,949:
{{Trans|Haskell}}{{Trans|JavaScript}}
{{Works with|Python|3.7}}
<
from itertools import chain
Line 4,068:
# MAIN ---
if __name__ == '__main__':
main()</
{{Out}}
<pre>Narcissistic numbers of digit lengths 1 to 7:
Line 4,082:
=={{header|Quackery}}==
<
[ 10 /mod
rot join swap
Line 4,098:
[ tuck join swap ]
1+ over size 25 = until ]
drop echo</
{{out}}
Line 4,107:
===For loop solution===
This is a slow method and it needed above 5 minutes on a i3 machine.
<
j <- nchar(u)
set2 <- c()
Line 4,118:
}
if (sum(control) == u) print(u)
}</
{{out}}
<pre>
Line 4,153:
*As we are using format anyway, we take the chance to make the output look nicer.
<
{
resultCount <- i <- 0
Line 4,164:
}
}
generateArmstrong(25)</
{{out}}
<pre>Armstrong number 1: 0
Line 4,193:
=={{header|Racket}}==
<
;; definitions.
;;
Line 4,256:
(n (sequence-filter narcissitic? (in-naturals 1)))) n)
'(1 2 3 4 5 6 7 8 9 153 370 371))
(check-equal? (next-narcissitics 0 12) '(1 2 3 4 5 6 7 8 9 153 370 371)))</
{{out}}
Line 4,264:
===Faster Version===
This version uses lists of digits, rather than numbers themselves.
<
(define (non-decrementing-digital-sequences L)
(define (inr d l)
Line 4,322:
(check-equal? (narcissitic-numbers-of-length<= 1) '(0 1 2 3 4 5 6 7 8 9))
(check-equal? (narcissitic-numbers-of-length<= 3) '(0 1 2 3 4 5 6 7 8 9 153 370 371 407)))</
{{out}}
Line 4,332:
===Simple, with concurrency===
Simple implementation is not exactly speedy, but concurrency helps move things along.
<syntaxhighlight lang="raku"
my @N = lazy (0..∞).hyper.grep: *.&is-narcissistic;
@N[^25].join(' ').say;</
{{out}}
<pre>0 1 2 3 4 5 6 7 8 9 153 370 371 407 1634 8208 9474 54748 92727 93084 548834 1741725 4210818 9800817 9926315</pre>
Line 4,340:
===Single-threaded, with precalculations===
This version that precalculates the values for base 1000 digits, but despite the extra work ends up taking more wall-clock time than the simpler version.
<syntaxhighlight lang="raku"
my int $i = $n;
my int $b = 1000;
Line 4,357:
say $l++, "\t", $_ if .&is-narcissistic for 10**($d-1) ..^ 10**$d;
last if $l > 25
};</
{{out}}
<pre>1 0
Line 4,387:
=={{header|REXX}}==
===idiomatic===
<
numeric digits 39 /*be able to handle largest Armstrong #*/
parse arg N . /*obtain optional argument from the CL.*/
Line 4,403:
#=# + 1 /*bump count of narcissistic numbers. */
say right(#, 9) ' narcissistic:' j /*display index and narcissistic number*/
end /*j*/ /*stick a fork in it, we're all done. */</
{{out|output|text= when using the default input:}}
<pre>
Line 4,437:
It is about '''77%''' faster then 1<sup>st</sup> REXX version.
<
numeric digits 39 /*be able to handle largest Armstrong #*/
parse arg N . /*obtain optional argument from the CL.*/
Line 4,459:
#=# + 1 /*bump count of narcissistic numbers. */
say right(#, 9) ' narcissistic:' j /*display index and narcissistic number*/
end /*j*/ /*stick a fork in it, we're all done. */</
{{out|output|text= is identical to the 1<sup>st</sup> REXX version.}}
Line 4,469:
It is about '''44%''' faster then 2<sup>nd</sup> REXX version, and
<br>it is about '''154%''' faster then 1<sup>st</sup> REXX version.
<
numeric digits 39 /*be able to handle largest Armstrong #*/
parse arg N . /*obtain optional argument from the CL.*/
Line 4,499:
say right(#,9) ' narcissistic:' arg(1) /*display index and narcissistic number*/
if #==n & n<11 then exit /*finished showing of narcissistic #'s?*/
return /*return to invoker & keep on truckin'.*/</
{{out|output|text= is identical to the 1<sup>st</sup> REXX version.}}
Line 4,508:
<br>it is about '''136%''' faster then 2<sup>nd</sup> REXX version, and
<br>it is about '''317%''' faster then 1<sup>st</sup> REXX version.
<
numeric digits 39 /*be able to handle largest Armstrong #*/
parse arg N . /*obtain optional argument from the CL.*/
Line 4,547:
say right(#,9) ' narcissistic:' arg(1) /*display index and narcissistic number*/
if #==n & n<11 then exit /*finished showing of narcissistic #'s?*/
return /*return to invoker & keep on truckin'.*/</
{{out|output|text= is identical to the 1<sup>st</sup> REXX version.}}
Line 4,554:
=={{header|Ring}}==
<
n = 0
count = 0
Line 4,575:
nr = (sum = n)
return nr
</syntaxhighlight>
=={{header|Ruby}}==
<
def narcissistic?
return false if negative?
Line 4,587:
end
puts 0.step.lazy.select(&:narcissistic?).first(25)</
{{out}}
<pre>
Line 4,618:
=={{header|Rust}}==
<
fn is_narcissistic(x: u32) -> bool {
let digits: Vec<u32> = x
Line 4,644:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 4,676:
{{works with|Scala|2.9.x}}
<
val narc: Int => Int = n => (n.toString map (_.asDigit) map (math.pow(_, n.toString.size)) sum) toInt
Line 4,683:
println((Iterator from 0 filter isNarc take 25 toList) mkString(" "))
}</
Output:
Line 4,689:
=={{header|Sidef}}==
<
n.digits »**» n.len -> sum == n
}
Line 4,699:
break if (count == 25)
}
}</
{{out}}
<pre>
Line 4,731:
=={{header|Swift}}==
<
@inlinable
public var isNarcissistic: Bool {
Line 4,753:
let narcs = Array((0...).lazy.filter({ $0.isNarcissistic }).prefix(25))
print("First 25 narcissistic numbers are \(narcs)")</
{{out}}
Line 4,760:
=={{header|Tcl}}==
<
set m [string length $n]
for {set t 0; set N $n} {$N} {set N [expr {$N / 10}]} {
Line 4,778:
}
puts [join [firstNarcissists 25] ","]</
{{out}}
<pre>
Line 4,786:
=={{header|UNIX Shell}}==
{{works with|ksh93}}
<
integer n=$1 len=${#n} sum=0 i
for ((i=0; i<len; i++)); do
Line 4,799:
done
echo "${nums[*]}"
echo "elapsed: $SECONDS"</
{{output}}
Line 4,806:
=={{header|VBA}}==
{{trans|Phix}}<
Dim d As String: d = CStr(n)
Dim l As Integer: l = Len(d)
Line 4,828:
Loop
Debug.Print Join(s, ", ")
End Sub</
<pre>0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474, 54748, 92727, 93084, 548834, 1741725, 4210818, 9800817, 9926315</pre>
=={{header|VBScript}}==
<
i = 0
j = 0
Line 4,848:
End Function
WScript.StdOut.Write Narcissist(25)</
{{out}}
<pre>0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474, 54748, 92727, 93084, 548834, 1741725, 4210818, 9800817, 9926315,</pre>
Line 4,854:
=={{header|Wren}}==
{{trans|Go}}
<
var power = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var limit = 10
Line 4,876:
}
System.print(narc.call(25))</
{{out}}
Line 4,885:
=={{header|XPL0}}==
This is based on Ring's version for Own Digits Power Sum.
<
int A, B, T, I;
[T:= 1;
Line 4,910:
];
];
]</
{{out}}
Line 4,918:
=={{header|zkl}}==
<
ns,m := n.split(), ns.len() - 1;
ns.reduce('wrap(s,d){ z:=d; do(m){z*=d} s+z },0) == n
}</
Pre computing the first 15 powers of 0..9 for use as a look up table speeds things up quite a bit but performance is pretty underwhelming.
<
(1).pump(15,List,'wrap(p){ n.toFloat().pow(p).toInt() }) });
fcn isNarcissistic2(n){
m:=(n.numDigits - 1);
n.split().reduce('wrap(s,d){ s + powers[d][m] },0) == n
}</
Now stick a filter on a infinite lazy sequence (ie iterator) to create an infinite sequence of narcissistic numbers (iterator.filter(n,f) --> n results of f(i).toBool()==True).
<
ns(15).println();
ns(5).println();
ns(5).println();</
{{out}}
<pre>
Line 4,943:
=={{header|ZX Spectrum Basic}}==
Array index starts at 1. Only 1 character long variable names are allowed for For-Next loops. 8 Digits or higher numbers are displayed as floating point numbers. Needs about 2 hours (3.5Mhz)
<
2 FOR Y=0 TO 9: LET M(Y+1)=Y: NEXT Y
3 FOR N=1 TO 7
Line 4,981:
37 NEXT N
38 PRINT
39 PRINT "DONE"</
{{out}}
<pre>9 8
|