| Bytes | Lang | Time | Link |
|---|---|---|---|
| 027 | TIBASIC TI84 Plus CE Python | 250911T143715Z | madeforl |
| 015 | APLNARS | 250905T165922Z | Rosario |
| 035 | dc | 250904T114417Z | Toby Spe |
| 052 | CASIO BASIC CASIO fx9750GIII | 250425T185410Z | madeforl |
| 069 | Tcl | 181214T235843Z | sergiol |
| 012 | Uiua | 240319T022459Z | noodle p |
| 082 | Swift 5.9 | 240318T125341Z | macOSist |
| 005 | Vyxal 3 | 240318T120505Z | pacman25 |
| 006 | Thunno 2 | 230610T134218Z | The Thon |
| 007 | 05AB1E legacy | 161108T150919Z | Magic Oc |
| 010 | Pyth | 170901T181319Z | Mr. Xcod |
| 006 | Jelly | 170106T191818Z | lynn |
| 032 | Julia 1.0 | 220225T165939Z | amelies |
| 030 | Pari/GP | 181104T063401Z | alephalp |
| 044 | Excel | 210529T150413Z | Axuary |
| 006 | Vyxal | 210529T102628Z | emanresu |
| 010 | Brachylog | 190301T053320Z | Unrelate |
| 118 | Retina | 161108T164735Z | mbomb007 |
| 051 | Ly | 181104T084029Z | LyricLy |
| 022 | K ngn/k | 181104T050946Z | Thaufeki |
| 046 | Javascript ES6 | 180129T115302Z | Brian H. |
| 060 | Kotlin | 180129T113517Z | jrtapsel |
| 008 | APL Dyalog Unicode | 180129T100718Z | Adá |
| 038 | JavaScript ES7 | 170517T150133Z | Shaggy |
| 012 | CJam | 180129T054846Z | Esolangi |
| 011 | Pyt | 180105T005150Z | mudkip20 |
| 016 | Add++ | 180128T203552Z | caird co |
| 041 | JavaScript 7 | 180105T040839Z | l4m2 |
| 046 | JavaScript | 171004T105223Z | DanielIn |
| 107 | Swift 3.2 | 170918T175540Z | Eric |
| 024 | Perl 5 | 170914T132849Z | Xcali |
| 007 | Japt | 170518T163957Z | Shaggy |
| 048 | R | 131114T071417Z | plannapu |
| 053 | R | 131115T132911Z | flodel |
| 044 | Python 2 | 170521T140852Z | caird co |
| 054 | Bash | 170518T175854Z | marcosm |
| 058 | Befunge 98 | 170107T005733Z | MercyBea |
| 009 | Pushy | 170106T191201Z | FlipTack |
| 030 | Perl 6 | 170106T195421Z | Sean |
| 056 | JavaScript ES6 | 170106T183726Z | George R |
| 090 | Python | 161108T155842Z | Mitchell |
| 085 | Clojure | 161219T021836Z | clismiqu |
| 008 | Pyke | 161217T182530Z | Blue |
| 023 | K | 131114T153440Z | tmartin |
| nan | Perl | 161110T184136Z | Gabriel |
| 090 | Factor | 161111T175430Z | cat |
| 173 | R | 161111T162245Z | brendanj |
| 024 | k | 161111T135343Z | Paul Ker |
| 050 | JavaScript ES6 | 161110T184949Z | Grax32 |
| 084 | Java | 161108T191405Z | Hypino |
| 110 | Clojure | 161110T001802Z | Carcigen |
| 111 | C | 161108T174550Z | Aryaman |
| 056 | JavaScript | 161109T175728Z | Jonathan |
| 103 | C# | 161109T173528Z | Pete Ard |
| 007 | Jelly | 161108T175629Z | Erik the |
| 066 | Haskell | 161108T164931Z | Angs |
| 115 | Racket | 161108T161443Z | rnso |
| 056 | Python 3 | 131114T030823Z | danmcard |
| 058 | JavaScript 70 | 131115T145238Z | zzzzBov |
| 013 | Pyth | 140708T073609Z | izzyg |
| 057 | Python 2.7 | 140218T160535Z | undergro |
| 166 | Delphi | 140218T153423Z | Teun Pro |
| nan | 140110T110426Z | Eduard F | |
| 117 | C# | 140111T234005Z | It's |
| 093 | C | 140110T153253Z | Josh |
| 101 | Lua | 140110T152057Z | JuSTMOnI |
| 099 | Smalltalk | 131115T031230Z | Paul Ric |
| 058 | Powershell | 131114T204921Z | Rynant |
| 102 | Common Lisp | 131115T023144Z | Paul Ric |
| 064 | Bash | 131115T040046Z | user unk |
| 039 | Awk | 131115T130413Z | manatwor |
| 076 | Haskell 2010 | 131115T035445Z | Nathan B |
| 048 | Dc | 131114T203257Z | manatwor |
| 051 | Python 2.x | 131114T202417Z | user1354 |
| 018 | Kona | 131114T172843Z | tmartin |
| nan | Ruby | 131114T153232Z | histocra |
| 066 | PHP | 131114T144151Z | Vlad Pre |
| 092 | F# | 131114T083647Z | Smetad A |
| 015 | APL | 131114T065729Z | marinus |
| 023 | J | 131114T035712Z | rational |
| 016 | GolfScript | 131114T052551Z | Howard |
| 043 | Mathematica | 131114T044337Z | alephalp |
| 038 | Perl | 131114T023242Z | breadbox |
TI-BASIC (TI-84 Plus CE Python), 48 40 29 27 bytes
-11 bytes thanks to absoluteAquarian's TI-BASIC answer for a different question, which helped me shorten this down
Input N
int(10fPart(N₁₀^(-randIntNoRep(1,1+int(log(N
N=sum(Ans^dim(Ans
outputs 1/0
APL(NARS), 15 chars
{⍵=+/k*≢k←⍎¨⍕⍵}
test:
f←{⍵=+/k*≢k←⍎¨⍕⍵}
f 153
1
f 1634
1
m/⍨f¨m←⍳1000
1 2 3 4 5 6 7 8 9 153 370 371 407
dc, 35 bytes
?[1pq]sqddZsZ[A~lZ^rd0!=x+]dsxx=q0p
How it works
? # read input
[1pq]sq # define function q to print 1 and exit
ddZsZ # copy input and save digit count to Z
[ # function x
A~lZ^ # divide by 10, and exponentiate remainder
rd0!=x # recurse while quotient
+ # add to other digit powers
]dsxx # copy, define, execute
=q0p # if equals original number, print 1, else 0
CASIO BASIC (CASIO fx-9750GIII), 52 bytes
?→Str 1
For 1→N To StrLen(Str 1
Ans+Exp(StrMid(Str 1,N,1))^StrLen(Str 1
Next
Ans=Exp(Str 1
Uiua, 12 bytes
=/+ⁿ⧻.-@0°⋕.
Explanation:
-@0°⋕.
Convert the number to a list of digits.
ⁿ⧻.
Raise each to the power of the list's length.
=/+
Is this list's sum equal to the original?
Swift 5.9, 82 bytes
let f={n in"\(n+0)".reduce(0){i,y in"\(n)".reduce(1){x,_ in Int("\(y)")!*x}+i}==n}
Thunno 2, 6 bytes
dDl*S=
Explanation
dDl*S= # Implicit input -> 153
d # Cast to digits -> [1, 5, 3]
Dl # Push the length -> [1, 5, 3] 3
* # Exponentiate -> [1, 125, 27]
S # Sum the list -> 153
= # Equals the input? -> 1
# Implicit output
Jelly, 6 bytes
D*L$S=
D Get the digits of the input
*L$ Raise each element to power of its length
S Sum
= Equals input?
Vyxal, 8 6 bytes
f⁰Le∑=
f # Map each digit to integer
e # (for each) to the power of
⁰L # Input length
∑ # Is sum...
= # Equal to
# (Implicit input)?
-2 thx to lyxal.
Brachylog, 10 bytes
lg;?↔z^ᵐ+?
The predicate succeeds if the input is an Armstrong number and fails if it is not. If run as a full program, success prints true. and failure prints false.
lg;?↔z A list of pairs [a digit of input, the length of input].
^ᵐ A list of numbers where each is a digit of the input raised to the power of its length.
+ The sum of those numbers.
? Attempt to unify that sum with the input.
Retina, 118 bytes
Byte count assumes ISO 8859-1 encoding.
.*
$0 $0¶$0
(?<=^\d*)\d
x
(?=.*$)
¶
0¶
\d+
$*
¶(1+)
¶$1 $1
{`^x ?
}s`(?<=x.*)1(?=1* (1+))
$1
1*
1¶1
11
^(1*)¶+\1\b
Explanation
.* # Copy number 3 times. For Length, Unary, and Digits
$0 $0¶$0
(?<=^\d*)\d # Convert first copy to x's (Length)
x
(?=.*$) # Split up digits of last copy, each on their own line
¶
0¶ # Remove zeros, because they leave blank lines
\d+ # Convert to unary
$*
¶(1+) # Duplicate each separated digit
¶$1 $1
{`^x ? # While x's exist, remove an x ...
}s`(?<=x.*)1(?=1* (1+)) # and multiply each value by the digit (nth power)
$1
1* # Remove original digits
1¶1 # Remove lines between digits
11
^(1*)¶+\1\b # Match if values are equal
Javascript (ES6) 46 bytes - Not competing
n=>(s=[...''+n]).forEach(v=>n-=v**s.length)|!n
Explanation:
n=>
(s=[...''+n]) // Convert input to array of chars and assign to s
.forEach(v=> // Loop over s (returns undefined)
n-=v**s.length) // reduce input by char^length
| // undefined is falsy, so we OR
!n // OR with negated input
// returns 1 if 0, 0 otherwise
Kotlin, 60 bytes
map{Math.pow(it-'0'+0.0,length+0.0)}.sum()==this.toInt()+0.0
Beautified
map {
Math.pow(it - '0' + 0.0, length + 0.0)
}.sum() == this.toInt() + 0.0
Test
fun String.f() =
map{Math.pow(it-'0'+0.0,length+0.0)}.sum()==this.toInt()+0.0
fun main(args: Array<String>) {
(0..1000).filter { it.toString().f() }.forEach { println(it) }
}
TIO
APL (Dyalog Unicode), 8 bytesSBCS
Tacit prefix function taking the input as a string.
⍎≡1⊥⍎¨*≢
⍎ is the evaluated argument
≡ identical to
1⊥ the sum (lit. convert from base-1) of
⍎¨ the evaluated characters (i.e the digits)
* raised to the power of
≢ the tally of characters (i.e. digits)
JavaScript (ES7), 43 38 bytes
Takes input as a string.
n=>n==eval([...n,0].join`**n.length+`)
Try It
f=
n=>n==eval([...n,0].join`**n.length+`)
o.innerText=f(i.value="153")
oninput=_=>o.innerText=f(i.value)
<input id=i type=number><pre id=o>
CJam, 12 bytes
{_Ab_,f#:+=}
Explanation:
{ } anonymous block, input: 1634
b get digits in base
A 10: [1 6 3 4]
, take the length: 4
# and raise
f each element
_ of the list of digits
to that power: [1 1296 81 256]
: fold over
+ addition: 1634
= and compare
_ to the original: 1 (true)
Pyt, 11 bytes
ĐĐḶ⌊⁺⇹ą⇹^Ʃ=
Explanation:
Implicit input
ĐĐ Duplicate the input twice
Ḷ⌊⁺ Get number of digits in the input
⇹ą Convert input to array of digits
⇹^Ʃ sum the digits raised to the power of the number of digits
= equals input?
JavaScript 7, 41 Bytes
s=>[...s].map(x=>N+=x**s.length,N=0)|N==s
JavaScript 46 bytes
F=n=>![...n].reduce((x,c)=>x-(+c)**n.length,n)
console.log(F("153") == true)
console.log(F("370") == true)
console.log(F("371") == true)
console.log(F("152") == false)
console.log(F("150") == false)
Swift 3.2: 107 characters
Of course Swift is absolutely not a quick language but I thought I would try:
func n(s:String){let c=s.utf8.map{Double($0)-48};print(c.reduce(0){$0+pow($1,Double(c.count))}==Double(s))}
Japt, 14 9 7 bytes
¶ì_xpZÊ
Explanation
Implicit input of integer U.
ì_
Convert U to an array of digits (ì), pass it through a function and convert back to an integer after.
xpZÊ
Reduce by addition (x), raising each element to the power (p) of the length (Ê) of the array in the process.
¶
Check if the result is strictly equal to U.
R, 71 69 66 56 48
Reduced by 8 bytes thanks to @Giuseppe! The idea was to perform the integer division before the modulo operation.
i=nchar(a<-scan()):0;a==sum((a%/%10^i%%10)^i[1])
(3-year) old version with corresponding explanation:
i=nchar(a<-scan()):1;a==sum(((a%%10^i)%/%10^(i-1))^i[1])
a<-scan() takes a number (integer, real,...) as input (say 153 for the example).
i becomes a vector containing 3 to 1 (the number of characters of a being 3).
%% is vectorized so a%%10^i means a modulo 1000, 100 and 10: it therefore gives 153, 53, 3.
(a%%10^i)%/%10^(i-1) is the integer division of that vector by 100, 10, 1: therefore, 1, 5, 3.
We elevate that with the first element of i which is the number of characters (here digits) of a, i. e. 3, thus giving a vector containing 1, 125, 27 that we sum and compares to a.
R, 53 bytes
sum(scan(t=gsub("(.)","\\1 ",x<-scan()))^nchar(x))==x
The gsub regex inserts spaces in between characters, so that the scan function will be able to read the number into a vector of digits.
Python 2, 44 bytes
I think this is the shortest you can get for Python. Uses a lambda rather than a full program.
lambda s:sum(int(x)**len(`s`)for x in`s`)==s
Based off @danmcardle's answer.
Original answer, 51 bytes
lambda s:sum(map(lambda x:int(x)**len(`s`),`s`))==s
Bash, 54 bytes
echo $[ `printf "+%c**${#1}" $(fold -w1<<<$1)` == $1 ]
Takes input as parameter, outputs 1 if is narcissist, 0 if not.
fold prints each digit one per line, printf adds +<digit>**<length> forming the arithmetic expression which is evaluated and compared to the original input.
Befunge 98, 58 bytes
1-00p&:a\v
00g1+00p>:a%\a/:!kv
\:9`kv00gk:00gk*+>
@.!-$<
I'm sure this can be golfed further. I will take another look at it and add an explanation later...
Pushy, 9 bytes
Note that this answer is non-competing as Pushy postdates the challenge. However, I thought I'd post it because it's interestingly short for a simple stack-based language:
VsLKeS^=#
It works like this (how the two stacks would look for the example input is shown on the right):
\ Implicit input, for example 1634. [1634], []
V \ Copy into second stack. [1634], [1634]
s \ Split into individual digits [1,6,3,4], [1634]
L \ Push stack length [1,6,3,4,4], [1634]
Ke \ Raise all to this power [1,1296,81,256], [1634]
S \ Take sum [..., 1634], [1634]
^= \ Check equality with initial input [..., True], []
# \ Output this boolean (as 0/1)
Perl 6, 30 bytes
{$_==sum .comb.map(* **.comb)}
Pretty straightforward. The chars method would be more typically used to get the number of characters in the input string, but comb returns those characters as a list, which evaluates to the number of characters in numeric context, and saves us a byte.
JavaScript (ES6), 56 bytes
eval(`${n=prompt()}0`.split``.join(`**${n.length}+`))==n
Python, 90 Bytes
a,z=input(),[]
for x in list(a):z.append(int(x)**len(a))
print(1 if sum(z)==int(a) else 0)
Clojure, 85 bytes
#(= n(int(reduce +(vec(map#(Math/pow(Character/digit % 10)(count(str n)))(str n))))))
Usage is like so:
(#(...) {number})
Ungolfed (with commentary):
(defn narcissistic [n]
; The function is altered a bit, to improve readability.
; The double arrow means that a result of a function will get "chained"
; onto the next function as the last argument:
; (->> 1 (* 2) (+ 3)) -> (->> (* 2 1) (+ 3)) -> (+ 3 (* 2 1))
(->> n
; Converts it to a string, for the next function
; 153 -> "153"
str
; Converts the string to an array of characters,
; which is then raised to the powers equal to the length of the number:
; 153 -> (1.0 125.0 27.0)
(map (#(Math/pow (Character/digit % 10) (count (str n)))))
; Converts the array to a vector (reducing only works with vectors)
; (1.0 125.0 27.0) -> [1.0 125.0 27.0]
vec
; Reduces the vector by adding them
; [1.0 125.0 27.0] -> 153.0
(reduce +)
; Turns that into an integer
; 153.0 -> 153
int
; Checks if that's equal to the original n
; 153 = 153 -> true
(= n)))
Pyke, 8 bytes (noncompeting)
YQ`lL^sq
Q`l - len(str(input))
L^ - map(^ ** V)
Y - digits(input)
s - sum(^)
q - ^ == input
K, 24 23
{x=+/xexp["I"$'a]@#a:$x}
Shaved 1 char with reordering
{x=+/{x xexp#x}"I"$'$x}
Perl, 27 +3 = 30 bytes
Run with -F. Older versions of Perl might require you to run with -nF instead, if -F does not imply -n.
grep$;+=$_**$#F,@F;say$_==$
Prints 1 if narcissistic, prints nothing otherwise.
(thanks to @Dada for byte-count correction, and for -2 bytes)
Factor, 90 bytes
[ read [ length ] [ >array [ 1string ] map [ 10 base> ] map ] bi [ swap ^ ] with map sum ]
More readable and explained:
[
read ! input
[ length ] ! a function which gets the length
[ >array [ 1string ] map [ 10 base> ] map ] ! another which turns a number into an array
bi ! apply both to the string input
[ swap ^ ] with map sum ! raise each digit to the length power and sum
]
R, 173 Bytes
a=readline()
b=as.numeric(strsplit(as.character(a),"")[[1]])
x=(b)^length(b)
if(sum(x)==as.numeric(paste(b,sep="",collapse=""))){
print("true")
} else{
print("false")
}
k, 24 bytes
{x=+/*/(#$x)#,"I"$'$x}
JavaScript ES6, 50 bytes
v=>[...s=v+""].map(x=>v-=Math.pow(x,s.length))&&!v
Convert the number to a string and iterate through the digits, subtract the power computation from the original number use the ! operator to invert the logic so that a 0 result returns true and non-zero returns false.
Java - 84 bytes
(a,l)->{int s=0;for(byte c:a.getBytes())s+=Math.pow(c-48,l);return a.equals(""+s);};
Non-lambda version: 101 bytes:
boolean n(String a,int l){int s=0;for(byte c:a.getBytes())s+=Math.pow(c-48,l);return a.equals(""+s);}
Called like this:
interface X {
boolean n(String a, int l);
}
static X x = (a,l)->{int s=0;for(byte c:a.getBytes())s+=Math.pow(c-48,l);return a.equals(""+s);};
public static void main(String[] args) {
System.out.println(n("153",3));
System.out.println(n("1634",4));
System.out.println(n("123",3));
System.out.println(n("654",3));
}
Returns:
true
true
false
false
Clojure, 110 bytes
(fn[](let[s(read-line)p #(Integer/parseInt(str %))](=(p s)(reduce + 0(map #(int(Math/pow(p %)(count s)))s)))))
Reads in the user input, maps over the digits, raising each to a power equal to the number of digits in the number, then checks that the sum of the digits equals the number itself.
Ungolfed (and neatened up):
(defn narcissistic? []
(let [n-str (read-line)
parse #(Integer/parseInt (str %))
pow #(int (Math/pow % (count n-str)))
powd-digits (map #(pow (parse %)) n-str)]
(= (parse n-str) (reduce + 0 powd-digits))))
C, 252 220 225 111 bytes
int f(char *a){for(int i=0;i<strlen(a);i++){r+=((int)a[i]);for(int j=0;j<strlen(a);j++)r*=r;}return r==(int)a;}
Returns 0 if false and 1 if true. Thanks to @DrMcMoylex for saving many bytes and explaining stuff.
JavaScript, 56 characters
n=prompt();n.split('').reduce((a,i)=>a+i**n.length,0)==n
This makes use of the exponentiation operator, so you have to be running a modern browser for this to work.
C#, 103 Bytes
Golfed:
bool N(int n){double a=0;foreach(var d in n+""){a+=Math.Pow(int.Parse(d+""),n+"".Length);}return a==n;}
Ungolfed:
public bool N(int n)
{
double a = 0;
foreach (var digit in n.ToString())
{
a += Math.Pow(int.Parse(digit + ""), n.ToString().Length);
}
return a == n;
}
Testing:
Console.WriteLine(new NarcissisticNumber().N(153));
True
Console.WriteLine(new NarcissisticNumber().N(1634));
True
Jelly, 7 bytes (non-competing)
D*DL$S⁼
Or alternatively (uses 2 chains):
Dµ*LS⁼Ḍ
Explanation of the first code:
D* DL$S⁼ Main link (monadic). Arguments: z
⁸ (implicit) z
D List of digits of z
⁸ (implicit) z
D List of digits of z
L Length of z
$ Last two links as a monad
* Exponentiation with base x and exponent y
S Sum of z
⁸ (implicit) z
⁼ Check if x equals y
Haskell, 68 66 bytes
d 0=[]
d n=mod n 10:d(div n 10)
sum.(\a->map(^length a)a).d>>=(==)
Usage:
*Main> sum.(\a->map(^length a)a).d>>=(==) $ 1634
True
Racket 115 bytes
(let*((l(number->string n))(g(string-length l))(m(for/sum((i l))(expt(string->number(string i))g))))(if(= m n)1 0))
Ungolfed:
(define (f n)
(let* ((l (number->string n))
(g (string-length l))
(m (for/sum ((i l))
(expt (string->number(string i)) g))))
(if (= m n) 1 0)))
Testing:
(f 153)
(f 1634)
(f 123)
(f 654)
Output:
1
1
0
0
Python 3, 56 bytes
Not very obfuscated, but a simple solution.
s = input()
print(int(s)==sum(int(c)**len(s)for c in s))
JavaScript - 70 58 characters
for(i in a=b=prompt())b-=Math.pow(a[i],a.length)
alert(!b)
Note:
If you're testing this in your dev console on Stack Exchange, be aware that there are a number of non-standard properties added to
String.prototypethat will break this solution, such asString.prototype.formatUnicorn. Please be sure to test in a clean environment, such as onabout:blank.
Pyth, 13 characters
JwqvJsm^vdlJJ
Explanation:
Jw J=input()
^vdlJ eval(d)^len(J)
m^vdlJJ map each character in J to eval(d)^len(J)
qvJsm^vdlJJ print(eval(J)==sum(map each character in J to eval(d)^len(J)))
Python 2.7 - 57 chars
i=`input()`
print`sum(map(lambda x:int(x)**len(i),i))`==i
There is a shorter Python answer, but I might as well toss in my contribution.
i=`input()`
i is set to input() surrounded by backticks (which is surprisingly hard to type through SE's markdown interpreter). Surrounding x with backticks is equivalent to str(x). [backtick]input()[backtick] saves two characters over raw_input() in any case where we can assume the input is an int, which we're allowed to do:
Error checking for text strings or other invalid inputs is not required.
Once i is a string containing the user's input, the next line is run. I'll explain this one from the inside out:
map(lambda x:int(x)**len(i),i)
map is a function in Python that takes a function and an iterable as arguments and returns a list of each item in the iterable after having the function applied to it. Here I'm defining an anonymous function lambda x which converts x to a string and raises it to the power of the length of i. This map will return a list of each character in the string i raised to the correct power, and even nicely converts it to an int for us.
`sum(map(lambda x:int(x)**len(i),i))`
Here I take the sum of each value in the list returned from the map. If this sum is equal to the original input, we have a narcissistic number. To check this, we either have to convert this sum to a string or the input to an int. int() is two more characters than two backticks, so we convert this to a string the same way we did with the input.
print`sum(map(lambda x:int(x)**len(i),i))`==i
Compare it to i and print the result, and we're done.
Delphi - 166
uses System.SysUtils,math;var i,r,l:integer;s:string;begin r:=0;readln(s);l:=length(s);for I:=1to l do r:=round(r+power(strtoint(s[i]),l));writeln(inttostr(r)=s);end.
With indent
uses System.SysUtils,math;
var
i,r,l:integer;
s:string;
begin
r:=0;
readln(s);
l:=length(s);
for I:=1to l do
r:=round(r+power(strtoint(s[i]),l));
writeln(inttostr(r)=s);
end.
Not the sortest but my take.
Python 2.7: 59 60 chars
a=input();(0,1)[sum(int(i)**len(str(a))for i in str(a))==a]
C#, 117
using System.Linq;class A{int Main(string[] a){return a[0].Select(c=>c-'0'^a[0].Length).Sum()==int.Parse(a[0])?1:0;}}
C - 97 93 characters
a,b;main(c){scanf("%d",&c);b=c;for(;c;c/=10)a+=pow(c%10,(int)log10(b)+1);printf("%d",a==b);}
With indentation:
a,b;
main(c) {
scanf("%d",&c);
b=c;
for(;c;c/=10)
a+=pow(c%10,(int)log10(b)+1);
printf("%d",a==b);
}
Lua (101 chars)
Lua isn't known for being concise, but it was fun to try anyway.
for n in io.lines()do l,s=n:len(),0 for i=1,l do d=n:byte(i)s=s+(d-48)^l end print(s==tonumber(n))end
Improvements welcome.
Smalltalk - 102 99 characters
[:n|a:=n asString collect:[:e|e digitValue]as:Array.^n=(a collect:[:each|each raisedTo:a size])sum]
At the Workspace, send value: with the number, and Print It.
Powershell, 75 63 62 60 58
Edit: Updated per @Iszi's comment (note: this counts on $x not existing)
Edit: Added @Danko's changes.
[char[]]($x=$n=read-host)|%{$x-="$_*"*$n.length+1|iex};!$x
58 56 chars
If input is limited to 10 digits (includes all int32)
($x=$n=read-host)[0..9]|%{$x-="$_*"*$n.length+1|iex};!$x
Common Lisp - 116 102 characters
(defun f(m)(labels((l(n)(if(> n 0)(+(expt(mod n 10)(ceiling(log m 10)))(l(floor n 10)))0)))(= m(l m))))
Formatted:
(defun f(m)
(labels((l(n)
(if(> n 0)
(+(expt(mod n 10)(ceiling(log m 10)))
(l(floor n 10)))
0)))
(=(l m)m)))
Bash, 64 chars
for((a=$1;a>0;s+=(a%10)**${#1},a/=10));do :; done;echo $[s==$1]
a=$1;p=${#a};for((;a>0;a/=10));do s=$((s+(a%10)**p));done;echo $((s==$1))
Awk: 40 39 characters
{for(;i<NF;)s+=$(i+++1)**NF;$0=$0==s}1
Sample run:
bash-4.1$ awk -F '' '{for(;i<NF;)s+=$(i+++1)**NF;$0=$0==s}1' <<< '153'
1
bash-4.1$ awk -F '' '{for(;i<NF;)s+=$(i+++1)**NF;$0=$0==s}1' <<< '1634'
1
bash-4.1$ awk -F '' '{for(;i<NF;)s+=$(i+++1)**NF;$0=$0==s}1' <<< '2013'
0
Haskell 2010 - 76 characters
main=do x<-getLine;print$(==x)$show$sum$map((^length x).(+(-48)).fromEnum)x
Dc: 48 characters
[1pq]Sr?d0rdZSz[d10/r10%lz^rSh+Lhd0!=c]dScx+=r0p
Sample run:
bash-4.1$ dc -e '[1pq]Sr?d0rdZSz[d10/r10%lz^rSh+Lhd0!=c]dScx+=r0p' <<< '153'
1
bash-4.1$ dc -e '[1pq]Sr?d0rdZSz[d10/r10%lz^rSh+Lhd0!=c]dScx+=r0p' <<< '1634'
1
bash-4.1$ dc -e '[1pq]Sr?d0rdZSz[d10/r10%lz^rSh+Lhd0!=c]dScx+=r0p' <<< '2013'
0
Python 2.x - 51
Same concept as crazedgremlin's solution for Python 3.x:
s=input();print s==sum(int(c)**len(`s`)for c in`s`)
Kona, 18
...
{x=+/(0$'u)^#u:$x}
Ruby, 34+5=39
With command-line flags
ruby -nlaF|
Run
p eval [$F,0]*"**#{~/$/}+"+"==#$_"
Outputs true or false.
PHP, 80 74 66 chars
Very straightforward PHP solution:
<?for(;$i<$l=strlen($a=$argv[1]);)$s+=pow($a[$i++],$l);echo$s==$a;
It assumes error_reporting doesn't include notices, otherwise quite a few extra characters will be needed to initialize $s=0; and $i=0.
Thx @manatwork for shortening many chars.
F# - 92 chars
let n=stdin.ReadLine()
n|>Seq.map(fun x->pown(int x-48)n.Length)|>Seq.sum=int n|>printf"%b"
APL (15)
∆≡⍕+/(⍎¨∆)*⍴∆←⍞
Outputs 1 if true and 0 if false.
Explanation:
∆←⍞: read a line (as characters), store in∆(⍎¨∆)*⍴∆: evaluate each character in∆and raise it to the power⍴∆∆≡⍕+/: see if the input equals the string representation of the sum of these
J, 23 chars
(".=+/@("."0^#))(1!:1)1
(1!:1)1 is keyboard input (returning a string).
". converts input to a number; "0 specifies a rank (dimension) of 0, in other words, taking each character and converting it to a number.
^ is the power function and # is the length function, thus taking each digit to the power of the length of the string (equivalently, the number of digits).
+/ is just sum, and = is comparing the sum and number.
GolfScript, 16 characters
~.`:s{48-s,?-}/!
Input must be given on STDIN, output is 0 or 1 indicating non-narcissistic / narcissistic number.
Explanation of the code:
~ # Evaluate the input to get a number
. # Accumulator (initially the number itself)
`:s # Convert number to string and assign to variable s
{ # Loop over characters of the string
48- # Reduce character value by 48
s, # Push length of input number
? # Power
- # Subtract result from accumulator
}/
! # Not! (i.e. iff accumulator was zero it was a narcissistic number)
Mathematica, 43 chars
Tr[#^Length@#&@IntegerDigits@#]==#&@Input[]
Perl, 38 characters
perl -lpe '$@=y///c;$s+=$_**$@for/./g;$_=$_==$s'
A pretty straightforward implementation.
Here's a slightly different version that fits in 35 characters:
perl -lpe '$@=y///c;$s+=$_**$@for/./g;$_-=$s'
This version outputs a false value if the input is narcissistic, otherwise it outputs a (Perl-accepted) true value. One might argue that this backwards version falls within the limits of the challenge description, but upon reflection I decided not to. I'm not that desperate to improve my score. Yet.