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

1 2
3
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\$
1
  • \$\begingroup\$ 25 bytes \$\endgroup\$
    – Jo King
    Commented Nov 7, 2018 at 5:42
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\$
1
  • \$\begingroup\$ You could use strings as input and save a byte. \$\endgroup\$ Commented Sep 19, 2017 at 6:49
0
\$\begingroup\$

Perl 5, 24 bytes

21 bytes of code + 3 for -pF flags

for$i(@F){$_-=$i**@F}

Try it online!

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

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

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)

\$\endgroup\$
1
  • \$\begingroup\$ Is it necessary to convert c into number? \$\endgroup\$
    – l4m2
    Commented Jan 5, 2018 at 4:14
0
\$\begingroup\$

JavaScript 7, 41 Bytes

s=>[...s].map(x=>N+=x**s.length,N=0)|N==s
\$\endgroup\$
0
\$\begingroup\$

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?

Try it online!

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

CJam, 12 bytes

{_Ab_,f#:+=}

Try it online!

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

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>

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

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

TryItOnline

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

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

Tcl, 77 bytes

proc N n {expr [join [lmap d [split $n ""] {expr $d**[string le $n]}] +]==$n}

Try it online!

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

Excel, 44 bytes

=A1=SUM(MID(A1,SEQUENCE(LEN(A1)),1)^LEN(A1))

Link to Spreadsheet

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

Pari/GP, 30 bytes

n->[n-=d^#s|d<-s=digits(n)];!n

Try it online!

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

Pyth, 10 bytes

qsm^sdl`Q`

Verify the test cases.

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

Thunno 2, 6 bytes

dDl*S=

Attempt This Online!

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

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.