53
\$\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):

13 + 53 + 33 = 1 + 125 + 27 = 153

1634:

14 + 64 + 34 + 44 = 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 list, does not qualify.

OEIS A005188

\$\endgroup\$
  • 3
    \$\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 Jan 6 '17 at 21:51

73 Answers 73

2
\$\begingroup\$

Jelly, 6 bytes (non-competing)

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\$

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\$
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\$
  • \$\begingroup\$ It's supposed to output true or false (also needs to take input). \$\endgroup\$ – Timtech Jan 10 '14 at 11:46
  • \$\begingroup\$ @Timtech or 1 and 0 \$\endgroup\$ – Eduard Florinescu Jan 10 '14 at 14:05
  • \$\begingroup\$ @EduardFlorinescu Still needs to take input. \$\endgroup\$ – Iszi Jan 10 '14 at 14:12
  • \$\begingroup\$ @lszi now should work ;) \$\endgroup\$ – Eduard Florinescu Jan 10 '14 at 15:13
  • 2
    \$\begingroup\$ For converting boolean value to integer int(BoolExpr) is shorter than (0,1)[BoolExpr]. +(BoolExpr) even shorter. \$\endgroup\$ – AMK Jan 11 '14 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\$
  • \$\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 Nov 8 '16 at 17:56
  • \$\begingroup\$ @DrMcMoylex How would you know the output if I used return? There's nothing printed in the terminal... \$\endgroup\$ – Aryaman Nov 8 '16 at 18:48
  • \$\begingroup\$ You could write a small wrapper to print the return value of the function \$\endgroup\$ – DJMcMayhem Nov 8 '16 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 Nov 8 '16 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 Nov 9 '16 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\$
  • \$\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 Nov 11 '16 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\$
  • \$\begingroup\$ there's no need for a : after a monadic verb, #:r -> #r \$\endgroup\$ – ngn Nov 5 '18 at 17:53
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\$
  • \$\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\$ – Unrelated String Mar 1 at 6:30
0
\$\begingroup\$

R - 216

Here is a long-ish R attempt:

fnNar = function(x = NULL) {
  if(is.null(x)) x = readline('Enter a positive integer: ')
  digits = as.double(unlist(strsplit(as.character(x), split = '')))
  exponent = length(digits)
  return(x == sum(digits ^ exponent))
}

# test the function
fnNar()

# test the function
fnNar(153)
fnNar(1634)
fnNar(101)
\$\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\$
0
\$\begingroup\$

JavaScript (ES6), 56 bytes

eval(`${n=prompt()}0`.split``.join(`**${n.length}+`))==n
\$\endgroup\$
0
\$\begingroup\$

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.

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

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^=#

Try it online!

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

Bash, 54 bytes

echo $[ `printf "+%c**${#1}" $(fold -w1<<<$1)` == $1 ]

Try it online!

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.

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

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

Try it online!

Based off @danmcardle's answer.

Original answer, 51 bytes

lambda s:sum(map(lambda x:int(x)**len(`s`),`s`))==s

Try it online!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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