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
  • 5
    \$\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\$ Commented Jan 6, 2017 at 21:51

83 Answers 83

1 2
3
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\$
1
  • \$\begingroup\$ 25 bytes \$\endgroup\$ 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\$

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

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.