57
\$\begingroup\$

A Narcissistic Number is a number which is the sum of its own digits, each raised to the power of the number of digits.

For example, take \$153\$ (3 digits):

\$1^3 + 5^3 + 3^3 = 153\$

\$1634\$:

\$1^4 + 6^4 + 3^4 + 4^4 = 1634 = 1 + 1296 + 81 + 256 = 1634\$

The Challenge:

Your code must take input from the user and output True or False depending upon whether the given number is a Narcissistic Number.

Error checking for text strings or other invalid inputs is not required. 1 or 0 for the output is acceptable. Code that simply generates a list of Narcissistic Numbers, or checks the user input against a hardcoded list, does not qualify.

OEIS A005188

\$\endgroup\$
1
  • 4
    \$\begingroup\$ Is it ok if I output True if it's such a number, but anything else (in this case the number itself) if not? \$\endgroup\$
    – devRicher
    Commented Jan 6, 2017 at 21:51

79 Answers 79

2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

APL (Dyalog Unicode), 8 bytesSBCS

Tacit prefix function taking the input as a string.

⍎≡1⊥⍎¨*≢

Try it online!

 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)

\$\endgroup\$
2
\$\begingroup\$

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

Try it online


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
\$\endgroup\$
2
\$\begingroup\$

Julia 1.0, 32 bytes

!n=sum(digits(n).^ndigits(n))==n

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Jelly, 6 bytes

D*L$S=

Try it online!

D        Get the digits of the input
 *L$     Raise each element to power of its length
    S    Sum
     =   Equals input?
\$\endgroup\$
2
\$\begingroup\$

Uiua, 12 bytes

=/+ⁿ⧻.-@0°⋕.

Try it

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?

\$\endgroup\$
1
\$\begingroup\$

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]
\$\endgroup\$
6
  • \$\begingroup\$ It's supposed to output true or false (also needs to take input). \$\endgroup\$
    – Timtech
    Commented Jan 10, 2014 at 11:46
  • \$\begingroup\$ @Timtech or 1 and 0 \$\endgroup\$ Commented Jan 10, 2014 at 14:05
  • \$\begingroup\$ @EduardFlorinescu Still needs to take input. \$\endgroup\$
    – Iszi
    Commented Jan 10, 2014 at 14:12
  • \$\begingroup\$ @lszi now should work ;) \$\endgroup\$ Commented Jan 10, 2014 at 15:13
  • 2
    \$\begingroup\$ For converting boolean value to integer int(BoolExpr) is shorter than (0,1)[BoolExpr]. +(BoolExpr) even shorter. \$\endgroup\$
    – AMK
    Commented Jan 11, 2014 at 18:24
1
\$\begingroup\$

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)))
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
5
  • \$\begingroup\$ Welcome to the site! Some tips for you: 1) You have a lot of unnecessary whitespace. You could remove most of the newlines and spaces/indentation and it would still run fine. 2) A function is allowed, so you could return '1' or '0' instead of printing it. That would save a lot of bytes. 3) Since you're only doing one thing in each 'for' loop, you could join the inner code with the loop itself. For example: for(int i=0;i<strlen(a);r+=a[i++]) \$\endgroup\$
    – DJMcMayhem
    Commented Nov 8, 2016 at 17:56
  • \$\begingroup\$ @DrMcMoylex How would you know the output if I used return? There's nothing printed in the terminal... \$\endgroup\$
    – Aryaman
    Commented Nov 8, 2016 at 18:48
  • \$\begingroup\$ You could write a small wrapper to print the return value of the function \$\endgroup\$
    – DJMcMayhem
    Commented Nov 8, 2016 at 18:51
  • \$\begingroup\$ @DrMcMoylex Using printf instead of making a new function uses less bytes, I believe. Thanks for the welcome, btw! \$\endgroup\$
    – Aryaman
    Commented Nov 8, 2016 at 19:03
  • 1
    \$\begingroup\$ No that's not what I meant. I meant you don't need to print anything. Returning is a valid form of output. You could print the return value for testing, but your submission can just be a function. Then you won't need to parse input or print the output. For example 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;} \$\endgroup\$
    – DJMcMayhem
    Commented Nov 9, 2016 at 19:15
1
\$\begingroup\$

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)

\$\endgroup\$
1
  • \$\begingroup\$ grep$;+=$_**$#F,@F;say$_==$ to save two bytes ($; instead of $a, and grep...,@F instead of grep{...}@F). However, note that -F counts as 3 bytes (-, F and a space). \$\endgroup\$
    – Dada
    Commented Nov 11, 2016 at 18:27
1
\$\begingroup\$

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)))
\$\endgroup\$
1
\$\begingroup\$

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)
\$\endgroup\$
1
\$\begingroup\$

Befunge 98, 58 bytes

1-00p&:a\v
 00g1+00p>:a%\a/:!kv
 \:9`kv00gk:00gk*+>
@.!-$<

Try it Online!

I'm sure this can be golfed further. I will take another look at it and add an explanation later...

\$\endgroup\$
1
\$\begingroup\$

Add++, 16 bytes

L,BDdbLdXBcB`sA=

Try it online!

\$\endgroup\$
1
\$\begingroup\$

K (ngn/k), 22 bytes

{x~+/*/'(#:r)#'r:10\x}

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ there's no need for a : after a monadic verb, #:r -> #r \$\endgroup\$
    – ngn
    Commented Nov 5, 2018 at 17:53
  • \$\begingroup\$ Can get it down to 18 bytes with {x~+/*/&[10\x]'$x} \$\endgroup\$
    – coltim
    Commented Dec 8, 2020 at 21:15
1
\$\begingroup\$

Ly, 51 bytes

ns>lS0sp11[ppl:Isp>l<ysp>l<sp>,^<l`sy,=!]>&+s<<l=fp

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Brachylog, 10 bytes

lg;?↔z^ᵐ+?

Try it online!

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.
\$\endgroup\$
1
  • \$\begingroup\$ Originally, this was nine bytes, but I realized that if I gave it a number more than nine digits long it would stop acting correctly, as previously I hadn't put g in there and it worked by virtue of single-digit lengths being length-1 sequences of themselves. \$\endgroup\$ Commented Mar 1, 2019 at 6:30
1
\$\begingroup\$

Vyxal 3, 5 bytes

Lᵛ*∑=

Try it Online! cool

\$\endgroup\$
1
\$\begingroup\$

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}
\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

Jelly, 7 bytes (non-competing)

D*DL$S⁼

Try it online!

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
\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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))))
\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

k, 24 bytes

{x=+/*/(#$x)#,"I"$'$x}
\$\endgroup\$
0
\$\begingroup\$

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")
}
\$\endgroup\$
0
\$\begingroup\$

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
]       
\$\endgroup\$
0
\$\begingroup\$

Pyke, 8 bytes (noncompeting)

YQ`lL^sq

Try it here!

 Q`l     -   len(str(input))
    L^   -  map(^ ** V)
Y        -   digits(input)
      s  -  sum(^)
       q - ^ == input
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.