Narcissistic decimal number
You are encouraged to solve this task according to the task description, using any language you may know.
A Narcissistic decimal number is a non-negative integer, in which if there are digits in its decimal representation then the sum of all the individual digits of the decimal representation raised to the power is equal to .
For example, if is 153 then , the number of digits is 3 and we have and so 153 is a narcissistic decimal integer number.
The task is to generate and show here, the first 25 narcissistic integer numbers.
Note: , the first in the series.
C
It prints the first 25 numbers, though not in order... <lang c>#include <stdio.h>
- include <gmp.h>
- define MAX_LEN 81
mpz_t power[10]; mpz_t dsum[MAX_LEN + 1]; int cnt[10], len;
void check_perm(void) { char s[MAX_LEN + 1]; int i, c, out[10] = { 0 };
mpz_get_str(s, 10, dsum[0]); for (i = 0; s[i]; i++) { c = s[i]-'0'; if (++out[c] > cnt[c]) return; }
if (i == len) gmp_printf(" %Zd", dsum[0]); }
void narc_(int pos, int d) { if (!pos) { check_perm(); return; }
do { mpz_add(dsum[pos-1], dsum[pos], power[d]); ++cnt[d]; narc_(pos - 1, d); --cnt[d]; } while (d--); }
void narc(int n) { int i; len = n; for (i = 0; i < 10; i++) mpz_ui_pow_ui(power[i], i, n);
mpz_init_set_ui(dsum[n], 0);
printf("length %d:", n); narc_(n, 9); putchar('\n'); }
int main(void) { int i;
for (i = 0; i <= 10; i++) mpz_init(power[i]); for (i = 1; i <= MAX_LEN; i++) narc(i);
return 0; }</lang>
- Output:
length 1: 9 8 7 6 5 4 3 2 1 0 length 2: length 3: 407 371 370 153 length 4: 9474 8208 1634 length 5: 93084 92727 54748 length 6: 548834 length 7: 9926315 9800817 4210818 1741725 length 8: 88593477 24678051 24678050 length 9: 912985153 534494836 472335975 146511208 length 10: 4679307774 length 11: 94204591914 82693916578 49388550606 44708635679 42678290603 40028394225 32164049651 32164049650 length 12: length 13: length 14: 28116440335967 length 15: length 16: 4338281769391371 4338281769391370 length 17: 35875699062250035 35641594208964132 21897142587612075 length 18: ^C
D
Simple Version
<lang d>void main() {
import std.stdio, std.algorithm, std.conv, std.range;
immutable isNarcissistic = (in uint n) pure => n.text.map!(d => (d - '0') ^^ n.text.length).sum == n; writefln("%(%(%d %)\n%)", uint.max.iota.filter!isNarcissistic.take(25).chunks(5));
}</lang>
- Output:
0 1 2 3 4 5 6 7 8 9 153 370 371 407 1634 8208 9474 54748 92727 93084 548834 1741725 4210818 9800817 9926315
Fast Version
<lang d>import std.stdio, std.algorithm, std.range, std.array;
uint[] narcissists(in uint m) pure nothrow {
typeof(return) result;
foreach (immutable uint digits; 0 .. 10) { const digitPowers = 10.iota.map!(i => i ^^ digits).array;
foreach (immutable n; 10 ^^ (digits - 1) .. 10 ^^ digits) { uint div = n, digitPSum; while (div) { digitPSum += digitPowers[div % 10]; div /= 10; }
if (n == digitPSum) { result ~= n; if (result.length >= m) return result; } } }
assert(0);
}
void main() {
writefln("%(%(%d %)\n%)", 25.narcissists.chunks(5));
}</lang> With LDC2 compiler prints the same output in less than 0.3 seconds.
Faster Version
<lang d>import std.stdio, std.bigint, std.conv;
struct Narcissistics(TNum, uint maxLen) {
TNum[10] power; TNum[maxLen + 1] dsum; uint[10] count; uint len;
void checkPerm() const { uint[10] mout;
immutable s = dsum[0].text; foreach (immutable d; s) { immutable c = d - '0'; if (++mout[c] > count[c]) return; }
if (s.length == len) writef(" %d", dsum[0]); }
void narc2(in uint pos, uint d) { if (!pos) { checkPerm; return; }
do { dsum[pos - 1] = dsum[pos] + power[d]; count[d]++; narc2(pos - 1, d); count[d]--; } while (d--); }
void show(in uint n) { len = n; foreach (immutable i, ref p; power) p = TNum(i) ^^ n; dsum[n] = 0; writef("length %d:", n); narc2(n, 9); writeln; }
}
void main() {
enum maxLength = 16; Narcissistics!(ulong, maxLength) narc; //Narcissistics!(BigInt, maxLength) narc; // For larger numbers. foreach (immutable i; 1 .. maxLength + 1) narc.show(i);
}</lang>
- Output:
length 1: 9 8 7 6 5 4 3 2 1 0 length 2: length 3: 407 371 370 153 length 4: 9474 8208 1634 length 5: 93084 92727 54748 length 6: 548834 length 7: 9926315 9800817 4210818 1741725 length 8: 88593477 24678051 24678050 length 9: 912985153 534494836 472335975 146511208 length 10: 4679307774 length 11: 94204591914 82693916578 49388550606 44708635679 42678290603 40028394225 32164049651 32164049650 length 12: length 13: length 14: 28116440335967 length 15: length 16: 4338281769391371 4338281769391370
With LDC2 compiler and maxLength=16 the run-time is about 0.64 seconds.
J
<lang j>getDigits=: "."0@": NB. get digits from number isNarc=: (= +/@(] ^ #)@getDigits)"0 NB. test numbers for Narcissism</lang> Example Usage <lang j> (#~ isNarc) i.1e7 NB. display Narcissistic numbers 0 1 2 3 4 5 6 7 8 9 153 370 371 407 1634 8208 9474 54748 92727 93084 548834 1741725 4210818 9800817 9926315</lang>
Perl 6
Here is a straightforward, naive implementation. It works but takes ages. <lang perl6>sub is-narcissistic(Int $n) { $n == [+] $n.comb »**» $n.chars }
for 0 .. * {
if .&is-narcissistic {
.say; last if ++state$ >= 25;
}
}</lang>
- Output:
0 1 2 3 4 5 6 7 8 9 153 370 371 407 Ctrl-C
Here the program was interrupted but if you're patient enough you'll see all the 25 numbers.
Here's a faster version that precalculates the values for base 1000 digits: <lang perl6>sub kigits($n) {
my int $i = $n; my int $b = 1000; gather while $i { take $i % $b; $i = $i div $b; }
}
constant narcissistic = 0, (1..*).map: -> $d {
my @t = 0..9 X** $d; my @table = @t X+ @t X+ @t; sub is-narcissistic(\n) { n == [+] @table[kigits(n)] } gather take $_ if is-narcissistic($_) for 10**($d-1) ..^ 10**$d;
}
for narcissistic {
say ++state $n, "\t", $_; last if $n == 25;
}</lang>
- Output:
1 0 2 1 3 2 4 3 5 4 6 5 7 6 8 7 9 8 10 9 11 153 12 370 13 371 14 407 15 1634 16 8208 17 9474 18 54748 19 92727 20 93084 21 548834 22 1741725 23 4210818 24 9800817 25 9926315
Python
This solution pre-computes the powers once.
<lang python>from __future__ import print_function from itertools import count, islice
def narcissists():
for digits in count(0): digitpowers = [i**digits for i in range(10)] for n in range(int(10**(digits-1)), 10**digits): div, digitpsum = n, 0 while div: div, mod = divmod(div, 10) digitpsum += digitpowers[mod] if n == digitpsum: yield n
for i, n in enumerate(islice(narcissists(), 25), 1):
print(n, end=' ') if i % 5 == 0: print()
print()</lang>
- Output:
0 1 2 3 4 5 6 7 8 9 153 370 371 407 1634 8208 9474 54748 92727 93084 548834 1741725 4210818 9800817 9926315
Faster Version
<lang python>try:
import psyco psyco.full()
except:
pass
class Narcissistics:
def __init__(self, max_len): self.max_len = max_len self.power = [0] * 10 self.dsum = [0] * (max_len + 1) self.count = [0] * 10 self.len = 0 self.ord0 = ord('0')
def check_perm(self, out = [0] * 10): for i in xrange(10): out[i] = 0
s = str(self.dsum[0]) for d in s: c = ord(d) - self.ord0 out[c] += 1 if out[c] > self.count[c]: return
if len(s) == self.len: print self.dsum[0],
def narc2(self, pos, d): if not pos: self.check_perm() return
while True: self.dsum[pos - 1] = self.dsum[pos] + self.power[d] self.count[d] += 1 self.narc2(pos - 1, d) self.count[d] -= 1 if d == 0: break d -= 1
def show(self, n): self.len = n for i in xrange(len(self.power)): self.power[i] = i ** n self.dsum[n] = 0 print "length %d:" % n, self.narc2(n, 9) print
def main():
narc = Narcissistics(14) for i in xrange(1, narc.max_len + 1): narc.show(i)
main()</lang>
- Output:
length 1: 9 8 7 6 5 4 3 2 1 0 length 2: length 3: 407 371 370 153 length 4: 9474 8208 1634 length 5: 93084 92727 54748 length 6: 548834 length 7: 9926315 9800817 4210818 1741725 length 8: 88593477 24678051 24678050 length 9: 912985153 534494836 472335975 146511208 length 10: 4679307774 length 11: 94204591914 82693916578 49388550606 44708635679 42678290603 40028394225 32164049651 32164049650 length 12: length 13: length 14: 28116440335967
Racket
<lang racket>;; OEIS: A005188 defines these as positive numbers, so I will follow that definition in the function
- definitions.
- 0
- assuming it is represented as the single digit 0 (and not an empty string, which is not the
- usual convention for 0 in decimal), is not
- sum(0^0), which is 1. 0^0 is a strange one,
- wolfram alpha calls returns 0^0 as indeterminate -- so I will defer to the brains behind OEIS
- on the definition here, rather than copy what I'm seeing in some of the results here
- lang racket
- Included for the serious efficientcy gains we get from fxvectors vs. general vectors.
- We also use fx+/fx- etc. As it stands, they do a check for fixnumness, for safety.
- We can link them in as "unsafe" operations (see the documentation on racket/fixnum);
- but we get a result from this program quickly enough for my tastes.
(require racket/fixnum)
- uses a precalculated (fx)vector of powers -- caller provided, please.
(define (sub-narcissitic? N powered-digits)
(let loop ((n N) (target N)) (cond [(fx> 0 target) #f] [(fx= 0 target) (fx= 0 n)] [(fx= 0 n) #f] [else (loop (fxquotient n 10) (fx- target (fxvector-ref powered-digits (fxremainder n 10))))])))
- Can be used as standalone, since it doesn't require caller to care about things like order of
- magnitude etc. However, it *is* slow, since it regenerates the powered-digits vector every time.
(define (narcissitic? n) ; n is +ve
(define oom+1 (fx+ 1 (order-of-magnitude n))) (define powered-digits (for/fxvector ((i 10)) (expt i oom+1))) (sub-narcissitic? n powered-digits))
- next m primes > z
(define (next-narcissitics z m) ; naming convention following math/number-theory's next-primes
(let-values ([(i l) (for*/fold ((i (fx+ 1 z)) (l empty)) ((oom (in-naturals)) (dgts^oom (in-value (for/fxvector ((i 10)) (expt i (add1 oom))))) (n (in-range (expt 10 oom) (expt 10 (add1 oom)))) #:when (sub-narcissitic? n dgts^oom) ; everyone else uses ^C to break... ; that's a bit of a manual process, don't you think? #:final (= (fx+ 1 (length l)) m)) (values (+ i 1) (append l (list n))))]) l)) ; we only want the list
(module+ main
(next-narcissitics 0 25) ; here's another list... depending on whether you believe sloane or wolfram :-) (cons 0 (next-narcissitics 0 25)))
(module+ test
(require rackunit) ; example given at head of task (check-true (narcissitic? 153)) ; rip off the first 12 (and 0, since Armstrong numbers seem to be postivie) from ; http://oeis.org/A005188 for testing (check-equal? (for/list ((i (in-range 12)) (n (sequence-filter narcissitic? (in-naturals 1)))) n) '(1 2 3 4 5 6 7 8 9 153 370 371)) (check-equal? (next-narcissitics 0 12) '(1 2 3 4 5 6 7 8 9 153 370 371)))</lang>
- Output:
(1 2 3 4 5 6 7 8 9 153 370 371 407 1634 8208 9474 54748 92727 93084 548834 1741725 4210818 9800817 9926315 24678050) (0 1 2 ... 9926315)
REXX
idomatic
<lang rexx>/*REXX program to generate and display a number of narcissistic numbers.*/ numeric digits 39 /*be able to handle the largest #*/ parse arg N .; if N== then N=25 /*get number of narcissistic #'s.*/ N=min(N,89) /*there are 89 narcissistic #s.*/
- =0 /*number of narcissistic # so far*/
do j=0 until #==N; L=length(j) /*get the length of the J number.*/ s=left(j,1)**L /*1st digit in J raised to L pow.*/ do k=2 for L-1 until s>j /*perform for each digit in J. */ s=s + substr(j,k,1)**L /*add digit raised to pow to sum.*/ end /*k*/ /* [↑] calculate the rest of sum*/ if s\==j then iterate /*does sum equal to J? No ··· */ #=#+1 /*bump the narcissistic num count*/ say right(#,9) ' narcissistic:' j /*display index & narcissistic #.*/ end /*j*/ /* [↑] this list starts at 0. */ /*stick a fork in it, we're done.*/</lang>
output when using the default input:
1 narcissistic: 0 2 narcissistic: 1 3 narcissistic: 2 4 narcissistic: 3 5 narcissistic: 4 6 narcissistic: 5 7 narcissistic: 6 8 narcissistic: 7 9 narcissistic: 8 10 narcissistic: 9 11 narcissistic: 153 12 narcissistic: 370 13 narcissistic: 371 14 narcissistic: 407 15 narcissistic: 1634 16 narcissistic: 8208 17 narcissistic: 9474 18 narcissistic: 54748 19 narcissistic: 92727 20 narcissistic: 93084 21 narcissistic: 548834 22 narcissistic: 1741725 23 narcissistic: 4210818 24 narcissistic: 9800817 25 narcissistic: 9926315
optimized
This REXX version is optimized to pre-compute all the ten (single) digits raised to all possible powers (which is 39). <lang rexx>/*REXX program to generate and display a number of narcissistic numbers.*/ numeric digits 39 /*be able to handle the largest #*/ parse arg N .; if N== then N=25 /*get number of narcissistic #'s.*/ N=min(N,89) /*there are 89 narcissistic #s.*/
do w=1 for 39 /*generate tables: digits ^ L pow*/ do i=0 for 10; @.w.i=i**w; end /*build table of 10 digs ^ L pow.*/ end /*w*/ /* [↑] table is of a fixed size.*/
- =0 /*number of narcissistic # so far*/
do j=0 until #==N; L=length(j) /*get the length of the J number.*/ _=left(j,1) /*select the first digit to sum. */ s=@.L._ /*sum of the J digs ^ L (so far)*/ do k=2 for L-1 until s>j /*perform for each digit in J. */ _=substr(j,k,1) /*select the next digit to sum. */ s=s+@.L._ /*add digit raised to pow to sum.*/ end /*k*/ /* [↑] calculate the rest of sum*/ if s\==j then iterate /*does sum equal to J? No ··· */ #=#+1 /*bump the narcissistic num count*/ say right(#,9) ' narcissistic:' j /*display index & narcissistic #.*/ end /*j*/ /* [↑] this list starts at 0. */ /*stick a fork in it, we're done.*/</lang>
output is the same as 1st REXX version.
optimized, unrolled
This REXX version is optimized by unrolling part of the DO loop that sums the digits.
The unrolling also necessitated the special handling of one- and two-digit narcissistic numbers.
<lang rexx>/*REXX program to generate and display a number of narcissistic numbers.*/
numeric digits 39 /*be able to handle the largest #*/
parse arg N .; if N== then N=25 /*get number of narcissistic #'s.*/
N=min(N,89) /*there are 89 narcissistic #s.*/
do w=1 for 39 /*generate tables: digits ^ L pow*/ do i=0 for 10; @.w.i=i**w; end /*build table of 10 digs ^ L pow.*/ end /*w*/ /* [↑] table is of a fixed size.*/
- =0 /*number of narcissistic # so far*/
do low=0 for 10; call tell low; end /*handle the first one-digit nums*/ /* [↓] skip the 2-digit numbers.*/ do j=100; L=length(j) /*get the length of the J number.*/ _1=left(j,1); _2=substr(j,2,1) /*select 1st & 2nd digit to sum. */ _R=right(j,1) /*select the right digit to sum. */ s=@.L._1 + @.L._2 + @.L._R /*sum of the J digs ^ L (so far)*/ do k=3 for L-3 until s>j /*perform for each digit in J. */ _=substr(j,k,1) /*select the next digit to sum. */ s=s + @.L._ /*add digit raised to pow to sum.*/ end /*k*/ /* [↑] calculate the rest of sum*/ if s==j then call tell j /*does sum equal to J? Yes ···*/ end /*j*/ /* [↑] this list starts at 0. */
exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────TELL subroutine─────────────────────*/ tell: parse arg y /*get narcissistic # to display. */
- =#+1 /*bump the narcissistic # count. */
say right(#,9) ' narcissistic:' y /*display index & narcissistic #.*/ if #==N then exit /*stick a fork in it, we're done.*/ return /*return and keep on truckin'. */</lang> output is the same as 1st REXX version.
Tcl
<lang tcl>proc isNarcissistic {n} {
set m [string length $n] for {set t 0; set N $n} {$N} {set N [expr {$N / 10}]} {
incr t [expr {($N%10) ** $m}]
} return [expr {$n == $t}]
}
proc firstNarcissists {target} {
for {set n 0; set count 0} {$count < $target} {incr n} {
if {[isNarcissistic $n]} { incr count lappend narcissists $n }
} return $narcissists
}
puts [join [firstNarcissists 25] ","]</lang>
- Output:
0,1,2,3,4,5,6,7,8,9,153,370,371,407,1634,8208,9474,54748,92727,93084,548834,1741725,4210818,9800817,9926315