Jump to content

Narcissistic decimal number: Difference between revisions

m
syntax highlighting fixup automation
m (→‎{{header|Raku}}: split versions apart, add concurrency to 1st)
m (syntax highlighting fixup automation)
Line 32:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F narcissists(m)
[Int] result
L(digits) 0..
Line 49:
print(n, end' ‘ ’)
I (L.index + 1) % 5 == 0
print()</langsyntaxhighlight>
 
{{out}}
Line 62:
=={{header|Ada}}==
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
 
procedure Narcissistic is
Line 93:
Current := Current + 1;
end loop;
end Narcissistic;</langsyntaxhighlight>
 
{{out}}
Line 100:
=={{header|Agena}}==
Tested with Agena 2.9.5 Win32
<langsyntaxhighlight lang="agena">scope
# print the first 25 narcissistic numbers
 
Line 155:
io.writeline()
 
epocs</langsyntaxhighlight>
{{out}}
<pre>
Line 162:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68"># find some narcissistic decimal numbers #
 
# returns TRUE if n is narcissitic, FALSE otherwise; n should be >= 0 #
Line 194:
FI
OD;
print( ( newline ) )</langsyntaxhighlight>
{{out}}
<pre>
Line 202:
=={{header|ALGOL W}}==
{{Trans|Agena}}
<langsyntaxhighlight lang="algolw">begin
% print the first 25 narcissistic numbers %
 
Line 267:
write()
 
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 274:
 
=={{header|APL}}==
<langsyntaxhighlight lang="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>
</lang>
 
=={{header|AppleScript}}==
Line 322:
For an imperative hand-optimisation, and a contrasting view, see the variant approach below :-)
 
<langsyntaxhighlight AppleScriptlang="applescript">------------------------- NARCISSI -----------------------
 
-- isDaffodil :: Int -> Int -> Bool
Line 493:
end script
end if
end mReturn</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight AppleScriptlang="applescript">{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}</langsyntaxhighlight>
----
 
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.
 
<langsyntaxhighlight lang="applescript">(*
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)</langsyntaxhighlight>
 
{{output}}
<langsyntaxhighlight lang="applescript">{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}</langsyntaxhighlight>
 
=={{header|Arturo}}==
{{trans|REXX}}
<langsyntaxhighlight lang="rebol">powers: map 0..9 'x [
map 0..9 'y [
x ^ y
Line 612:
]
inc 'i
]</langsyntaxhighlight>
 
{{out}}
Line 643:
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">
<lang AutoHotkey>
#NoEnv ; Do not try to use environment variables
SetBatchLines, -1 ; Execute as quickly as you can
Line 686:
}
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 703:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f NARCISSISTIC_DECIMAL_NUMBER.AWK
BEGIN {
Line 720:
exit(0)
}
</syntaxhighlight>
</lang>
<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.
 
<langsyntaxhighlight lang="befunge">p55*\>:>:>:55+%\55+/00gvv_@
>1>+>^v\_^#!:<p01p00:+1<>\>
>#-_>\>20p110g>\20g*\v>1-v|
^!p00:-1g00+$_^#!:<-1<^\.:<</langsyntaxhighlight>
 
{{out}}
Line 743:
<code>B10</code> is a BQNcrate idiom to get the digits of a number.
 
<langsyntaxhighlight lang="bqn">B10 ← 10{⌽𝕗|⌊∘÷⟜𝕗⍟(↕1+·⌊𝕗⋆⁼1⌈⊢)}
IsNarc ← {𝕩=+´⋆⟜≠B10 𝕩}
 
/IsNarc¨ ↕1e7</langsyntaxhighlight><syntaxhighlight lang ="bqn">⟨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⟩</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight lang="bqn">/ ↕∘≠⊸= ∾ (⥊0+⌜´(0=↕)↓¨(<↕10)⋆⊢)¨↕8</langsyntaxhighlight>
 
=={{header|C}}==
Line 756:
 
The following prints the first 25 numbers, though not in order...
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <gmp.h>
 
Line 818:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 843:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">
using System;
 
Line 883:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 893:
</pre>
===or===
<langsyntaxhighlight lang="csharp">
//Narcissistic numbers: Nigel Galloway: February 17th., 2015
using System;
Line 922:
}
}
</syntaxhighlight>
</lang>
{{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.
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 1,072:
}
}
</syntaxhighlight>
</lang>
{{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++}}==
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <vector>
Line 1,305:
return system( "pause" );
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,313:
=={{header|Clojure}}==
Find N first Narcissistic numbers.
<syntaxhighlight lang="clojure">
<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>
</lang>
{{out}}
by Average-user
Line 1,337:
 
=={{header|COBOL}}==
<syntaxhighlight lang="cobol">
<lang COBOL>
PROGRAM-ID. NARCISSIST-NUMS.
DATA DIVISION.
Line 1,396:
END PROGRAM NARCISSIST-NUMS.
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,425:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="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>
</lang>
{{out}}
<pre>
Line 1,475:
=={{header|D}}==
===Simple Version===
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.algorithm, std.conv, std.range;
 
Line 1,482:
writefln("%(%(%d %)\n%)",
uint.max.iota.filter!isNarcissistic.take(25).chunks(5));
}</langsyntaxhighlight>
{{out}}
<pre>0 1 2 3 4
Line 1,492:
===Fast Version===
{{trans|Python}}
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.array;
 
uint[] narcissists(in uint m) pure nothrow @safe {
Line 1,520:
void main() {
writefln("%(%(%d %)\n%)", 25.narcissists.chunks(5));
}</langsyntaxhighlight>
With LDC2 compiler prints the same output in less than 0.3 seconds.
 
===Faster Version===
{{trans|C}}
<langsyntaxhighlight lang="d">import std.stdio, std.bigint, std.conv;
 
struct Narcissistics(TNum, uint maxLen) {
Line 1,578:
foreach (immutable i; 1 .. maxLength + 1)
narc.show(i);
}</langsyntaxhighlight>
{{out}}
<pre>length 1: 9 8 7 6 5 4 3 2 1 0
Line 1,600:
=={{header|Elixir}}==
{{trans|D}}
<langsyntaxhighlight lang="elixir">defmodule RC do
def narcissistic(m) do
Enum.reduce(1..10, [0], fn digits,acc ->
Line 1,631:
catch
x -> IO.inspect x
end</langsyntaxhighlight>
 
{{out}}
Line 1,640:
 
=={{header|ERRE}}==
<langsyntaxhighlight ERRElang="erre">PROGRAM NARCISISTIC
 
!$DOUBLE
Line 1,661:
N=N+1
END LOOP
END PROGRAM</langsyntaxhighlight>
Output
<pre>
Line 1,669:
 
=={{header|F Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
//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>
</lang>
{{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</langsyntaxhighlight>
{{out}}
<pre>
Line 1,730:
=={{header|Forth}}==
{{works with|GNU Forth|0.7.0}}
<langsyntaxhighlight lang="forth">
: dig.num \ returns input number and the number of its digits ( n -- n n1 )
dup
Line 1,810:
25 narc.num
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,843:
=={{header|FreeBASIC}}==
===Simple Version===
<langsyntaxhighlight FreeBASIClang="freebasic">' normal version: 14-03-2017
' 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</langsyntaxhighlight>
{{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>
<langsyntaxhighlight FreeBASIClang="freebasic">' gmp version: 17-06-2015
' uses gmp
' compile with: fbc -s console
Line 2,036:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
Left side: program output, right side: sorted on length, value
Line 2,130:
 
=={{header|FunL}}==
<langsyntaxhighlight lang="funl">def narcissistic( start ) =
power = 1
powers = array( 0..9 )
Line 2,149:
narc( start )
 
println( narcissistic(0).take(25) )</langsyntaxhighlight>
 
{{out}}
Line 2,167:
=={{header|Go}}==
Nothing fancy as it runs in a fraction of a second as-is.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 2,195:
func main() {
fmt.Println(narc(25))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,204:
{{trans|FreeBASIC}}
Maximum for N (double) is14 digits, there are no 15 digits numbers
<langsyntaxhighlight lang="qbasic">1 DEFINT A-W : DEFDBL X-Z : DIM D(9) : DIM X2(9) : KEY OFF : CLS
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</langsyntaxhighlight>
{{out}}
<pre> 9 8 7 6 5
Line 2,244:
=={{header|Haskell}}==
===Exhaustive search (integer series)===
<langsyntaxhighlight Haskelllang="haskell">import Data.Char (digitToInt)
 
isNarcissistic :: Int -> Bool
Line 2,253:
 
main :: IO ()
main = mapM_ print $ take 25 (filter isNarcissistic [0 ..])</langsyntaxhighlight>
 
===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.
 
<langsyntaxhighlight lang="haskell">import Data.Bifunctor (second)
 
narcissiOfLength :: Int -> [Int]
Line 2,306:
w = maximum (length . xShow <$> xs)
in unlines $
s : fmap (((++) . rjust w ' ' . xShow) <*> ((" -> " ++) . fxShow . f)) xs</langsyntaxhighlight>
{{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:
<langsyntaxhighlight lang="unicon">procedure main(A)
limit := integer(A[1]) | 25
every write(isNarcissitic(seq(0))\limit)
Line 2,331:
every (sum := 0) +:= (!sn)^m
return sum = n
end</langsyntaxhighlight>
 
Sample run:
Line 2,365:
 
=={{header|J}}==
<langsyntaxhighlight lang="j">getDigits=: "."0@": NB. get digits from number
isNarc=: (= +/@(] ^ #)@getDigits)"0 NB. test numbers for Narcissism</langsyntaxhighlight>
'''Example Usage'''
<langsyntaxhighlight lang="j"> (#~ isNarc) i.1e7 NB. display Narcissistic numbers
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</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java5">public class Narc{
public static boolean isNarc(long x){
if(x < 0) return false;
Line 2,395:
}
}
}</langsyntaxhighlight>
{{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!
<langsyntaxhighlight lang="java5">
import java.util.stream.IntStream;
public class NarcissisticNumbers {
Line 2,427:
});
}
}</langsyntaxhighlight>
{{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}}
<langsyntaxhighlight lang="javascript">function isNarc(x) {
var str = x.toString(),
i,
Line 2,457:
}
return n.join(' ');
}</langsyntaxhighlight>
{{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)====
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
Line 2,502:
)
.narc
})();</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight JavaScriptlang="javascript">[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]</langsyntaxhighlight>
 
 
Line 2,514:
 
(Generating the unordered digit combinations directly as power sums allows faster testing later, and needs less space)
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 2,657:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{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:
<langsyntaxhighlight lang="jq">def is_narcissistic:
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;</langsyntaxhighlight>
 
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:
<langsyntaxhighlight lang="jq"># Input: [i, [0^i, 1^i, 2^i, ..., 9^i]]
# 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;</langsyntaxhighlight>
 
The function is_narcisstic can now be modified to use powers(j) as follows:
<langsyntaxhighlight lang="jq"># Input: [n, [i, [0^i, 1^i, 2^i,...]]] where i is the number of digits in n.
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;</langsyntaxhighlight>
'''The task'''
<langsyntaxhighlight lang="jq"># If your jq has "while", then feel free to omit the following definition:
def while(cond; update):
def _while: if cond then ., (update | _while) else empty end;
Line 2,725:
| "\(.[2]): \(.[0])" ;
 
narcissistic(25)</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="sh">jq -r -n -f Narcissitic_decimal_number.jq
1: 0
2: 1
Line 2,752:
23: 4210818
24: 9800817
25: 9926315</langsyntaxhighlight>
 
=={{header|Julia}}==
This easy to implement brute force technique is plenty fast enough to find the first few Narcissistic decimal numbers.
<langsyntaxhighlight Julialang="julia">using Printf # for Julia version 1.0+
 
function isnarcissist(n, b=10)
Line 2,779:
findnarcissist()
@time findnarcissist(true)
</langsyntaxhighlight>{{out}}
<pre>
Finding the first 25 Narcissistic numbers:
Line 2,811:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.0
 
fun isNarcissistic(n: Int): Boolean {
Line 2,839:
}
while (count < 25)
}</langsyntaxhighlight>
 
{{out}}
Line 2,848:
 
=={{header|Ksh}}==
<langsyntaxhighlight lang="ksh">
#!/bin/ksh
 
Line 2,889:
_isnarcissist ${i} ; (( $? )) && printf "%3d. %d\n" $(( ++cnt )) ${i}
done
</syntaxhighlight>
</lang>
{{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.
<langsyntaxhighlight Lualang="lua">function isNarc (n)
local m, sum, digit = string.len(n), 0
for pos = 1, m do
Line 2,935:
end
n = n + 1
until count == 25</langsyntaxhighlight>
{{out}}
<pre>
Line 2,942:
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
 
Narc:=proc(i)
Line 2,966:
end do:
NDN;
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">narc[1] = 0;
narc[n_] := narc[n] = NestWhile[# + 1 &, narc[n - 1] + 1, Plus @@ (IntegerDigits[#]^IntegerLength[#]) != # &];
narc /@ Range[25]</langsyntaxhighlight>
{{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}}==
<langsyntaxhighlight MATLABlang="matlab">function testNarcissism
x = 0;
c = 0;
Line 2,992:
dig = sprintf('%d', n) - '0';
tf = n == sum(dig.^length(dig));
end</langsyntaxhighlight>
{{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}}==
<langsyntaxhighlight Nanoquerylang="nanoquery">def is_narcissist(num)
digits = {}
for digit in str(num)
Line 3,029:
print num + " "
end
println</langsyntaxhighlight>
{{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.
<langsyntaxhighlight Nimlang="nim">import sequtils, strutils
 
func digits(n: Natural): seq[int] =
Line 3,061:
m *= 10
 
echo findNarcissistic(25).join(" ")</langsyntaxhighlight>
 
{{out}}
Line 3,068:
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: isNarcissistic(n)
| 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>
</lang>
 
{{out}}
Line 3,088:
=={{header|PARI/GP}}==
Naive code, could be improved by splitting the digits in half and meeting in the middle.
<langsyntaxhighlight lang="parigp">isNarcissistic(n)=my(v=digits(n)); sum(i=1, #v, v[i]^#v)==n
v=List();for(n=1,1e9,if(isNarcissistic(n),listput(v,n);if(#v>24, return(Vec(v)))))</langsyntaxhighlight>
{{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).
<langsyntaxhighlight lang="pascal">
program NdN;
//Narcissistic decimal number
Line 3,178:
NextPowDig;
end;
end.</langsyntaxhighlight>
;output:
<pre>
Line 3,196:
recursive solution.Just counting the different combination of digits<BR>
See [[Combinations_with_repetitions]]<BR>
<langsyntaxhighlight lang="pascal">program PowerOwnDigits;
{$IFDEF FPC}
{$MODE DELPHI}{$OPTIMIZATION ON,ALL}{$COPERATORS ON}
Line 3,398:
{$ENDIF}
end.
</syntaxhighlight>
</lang>
{{out|@TIO.RUN}}
<pre style="height:180px">
Line 3,464:
=={{header|Perl}}==
Simple version using a naive predicate.
<langsyntaxhighlight lang="perl">use v5.36;
 
sub is_narcissistic ($n) {
Line 3,478:
}
 
say join ' ', @N;</langsyntaxhighlight>
{{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}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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>
<!--</langsyntaxhighlight>-->
{{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.
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 3,605:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(let (C 25 N 0 L 1)
(loop
(when
Line 3,617:
(T (=0 C) 'done) ) )
(bye)</langsyntaxhighlight>
 
=={{header|PL/I}}==
===version 1===
{{trans|REXX}}
<langsyntaxhighlight lang="pli"> narn: Proc Options(main);
Dcl (j,k,l,nn,n,sum) Dec Fixed(15)init(0);
Dcl s Char(15) Var;
Line 3,673:
Return(result);
End
End;</langsyntaxhighlight>
{{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;</langsyntaxhighlight>
{{out}}
<pre> 1 narcissistic: 0 0 00:41:43.632
Line 3,798:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Test-Narcissistic ([int]$Number)
{
Line 3,829:
 
$narcissisticNumbers | Format-Wide {"{0,7}" -f $_} -Column 5 -Force
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 3,843:
This solution pre-computes the powers once.
 
<langsyntaxhighlight lang="python">from __future__ import print_function
from itertools import count, islice
 
Line 3,860:
print(n, end=' ')
if i % 5 == 0: print()
print()</langsyntaxhighlight>
 
{{out}}
Line 3,872:
 
{{trans|D}}
<langsyntaxhighlight lang="python">try:
import psyco
psyco.full()
Line 3,929:
narc.show(i)
 
main()</langsyntaxhighlight>
{{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}}
<langsyntaxhighlight lang="python">'''Narcissistic decimal numbers'''
 
from itertools import chain
Line 4,068:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Narcissistic numbers of digit lengths 1 to 7:
Line 4,082:
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ [] swap
[ 10 /mod
rot join swap
Line 4,098:
[ tuck join swap ]
1+ over size 25 = until ]
drop echo</langsyntaxhighlight>
 
{{out}}
Line 4,107:
===For loop solution===
This is a slow method and it needed above 5 minutes on a i3 machine.
<langsyntaxhighlight lang="rsplus">for (u in 1:10000000) {
j <- nchar(u)
set2 <- c()
Line 4,118:
}
if (sum(control) == u) print(u)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 4,153:
*As we are using format anyway, we take the chance to make the output look nicer.
 
<langsyntaxhighlight lang="rsplus">generateArmstrong <- function(howMany)
{
resultCount <- i <- 0
Line 4,164:
}
}
generateArmstrong(25)</langsyntaxhighlight>
{{out}}
<pre>Armstrong number 1: 0
Line 4,193:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">;; OEIS: A005188 defines these as positive numbers, so I will follow that definition in the function
;; 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)))</langsyntaxhighlight>
 
{{out}}
Line 4,264:
===Faster Version===
This version uses lists of digits, rather than numbers themselves.
<langsyntaxhighlight lang="racket">#lang racket
(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)))</langsyntaxhighlight>
 
{{out}}
Line 4,332:
===Simple, with concurrency===
Simple implementation is not exactly speedy, but concurrency helps move things along.
<syntaxhighlight lang="raku" perl6line>sub is-narcissistic(Int $n) { $n == [+] $n.comb »**» $n.chars }
my @N = lazy (0..∞).hyper.grep: *.&is-narcissistic;
@N[^25].join(' ').say;</langsyntaxhighlight>
{{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" perl6line>sub kigits($n) {
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
};</langsyntaxhighlight>
{{out}}
<pre>1 0
Line 4,387:
=={{header|REXX}}==
===idiomatic===
<langsyntaxhighlight lang="rexx">/*REXX program generates and displays a number of narcissistic (Armstrong) numbers. */
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. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 4,437:
 
It is about &nbsp; '''77%''' &nbsp; faster then 1<sup>st</sup> REXX version.
<langsyntaxhighlight lang="rexx">/*REXX program generates and displays a number of narcissistic (Armstrong) numbers. */
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. */</langsyntaxhighlight>
{{out|output|text=&nbsp; is identical to the 1<sup>st</sup> REXX version.}}
 
Line 4,469:
It is about &nbsp; &nbsp; '''44%''' &nbsp; faster then 2<sup>nd</sup> REXX version, &nbsp; and
<br>it is about &nbsp; '''154%''' &nbsp; faster then 1<sup>st</sup> REXX version.
<langsyntaxhighlight lang="rexx">/*REXX program generates and displays a number of narcissistic (Armstrong) numbers. */
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'.*/</langsyntaxhighlight>
{{out|output|text=&nbsp; is identical to the 1<sup>st</sup> REXX version.}}
 
Line 4,508:
<br>it is about &nbsp; '''136%''' &nbsp; faster then 2<sup>nd</sup> REXX version, &nbsp; and
<br>it is about &nbsp; '''317%''' &nbsp; faster then 1<sup>st</sup> REXX version.
<langsyntaxhighlight lang="rexx">/*REXX program generates and displays a number of narcissistic (Armstrong) numbers. */
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'.*/</langsyntaxhighlight>
{{out|output|text=&nbsp; is identical to the 1<sup>st</sup> REXX version.}}
 
Line 4,554:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
n = 0
count = 0
Line 4,575:
nr = (sum = n)
return nr
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">class Integer
def narcissistic?
return false if negative?
Line 4,587:
end
 
puts 0.step.lazy.select(&:narcissistic?).first(25)</langsyntaxhighlight>
{{out}}
<pre>
Line 4,618:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">
fn is_narcissistic(x: u32) -> bool {
let digits: Vec<u32> = x
Line 4,644:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,676:
{{works with|Scala|2.9.x}}
 
<langsyntaxhighlight Scalalang="scala">object NDN extends App {
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(" "))
 
}</langsyntaxhighlight>
 
Output:
Line 4,689:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func is_narcissistic(n) {
n.digits »**» n.len -> sum == n
}
Line 4,699:
break if (count == 25)
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 4,731:
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">extension BinaryInteger {
@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)")</langsyntaxhighlight>
 
{{out}}
Line 4,760:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc isNarcissistic {n} {
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] ","]</langsyntaxhighlight>
{{out}}
<pre>
Line 4,786:
=={{header|UNIX Shell}}==
{{works with|ksh93}}
<langsyntaxhighlight lang="bash">function narcissistic {
integer n=$1 len=${#n} sum=0 i
for ((i=0; i<len; i++)); do
Line 4,799:
done
echo "${nums[*]}"
echo "elapsed: $SECONDS"</langsyntaxhighlight>
 
{{output}}
Line 4,806:
 
=={{header|VBA}}==
{{trans|Phix}}<langsyntaxhighlight lang="vb">Private Function narcissistic(n As Long) As Boolean
Dim d As String: d = CStr(n)
Dim l As Integer: l = Len(d)
Line 4,828:
Loop
Debug.Print Join(s, ", ")
End Sub</langsyntaxhighlight>{{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|VBScript}}==
<langsyntaxhighlight lang="vb">Function Narcissist(n)
i = 0
j = 0
Line 4,848:
End Function
 
WScript.StdOut.Write Narcissist(25)</langsyntaxhighlight>
{{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}}
<langsyntaxhighlight lang="ecmascript">var narc = Fn.new { |n|
var power = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var limit = 10
Line 4,876:
}
 
System.print(narc.call(25))</langsyntaxhighlight>
 
{{out}}
Line 4,885:
=={{header|XPL0}}==
This is based on Ring's version for Own Digits Power Sum.
<langsyntaxhighlight XPL0lang="xpl0">func IPow(A, B); \A^B
int A, B, T, I;
[T:= 1;
Line 4,910:
];
];
]</langsyntaxhighlight>
 
{{out}}
Line 4,918:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn isNarcissistic(n){
ns,m := n.split(), ns.len() - 1;
ns.reduce('wrap(s,d){ z:=d; do(m){z*=d} s+z },0) == n
}</langsyntaxhighlight>
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.
<langsyntaxhighlight lang="zkl">var [const] powers=(10).pump(List,'wrap(n){
(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
}</langsyntaxhighlight>
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).
<langsyntaxhighlight lang="zkl">ns:=[0..].filter.fp1(isNarcissistic);
ns(15).println();
ns(5).println();
ns(5).println();</langsyntaxhighlight>
{{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)
<langsyntaxhighlight lang="zxbasic"> 1 DIM K(10): DIM M(10)
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"</langsyntaxhighlight>
{{out}}
<pre>9 8
10,333

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.