q programming challenge – Narcissistic Numbers

Jamie Grant kdb+ 6 Comments

This is the second in an occasional series of q challenges we’ll post on the blog. Please get involved by posting your own solutions in the comments (prior to revealing the solution). As we get through the backlog of challenges that have been posed and completed by the AquaQ team, future challenges will be conducted ‘live’ on the blog, with the best solutions picked from the comments.

Narcissistic Numbers

Puzzle 2 – Narcissistic Numbers

153 is the smallest narcissistic number greater than 10. It’s called narcissistic because when the digits are raised to the power of the count of the digits, you get the original number that is,

1^3 + 5^3 + 3^3 = 1+125+27=153

So the challenge for is using q code, to tell me what is the sum of all the narcissistic numbers between 10 and 2 million inclusive, using the shortest, fastest, q code you can.

Jamie Grantq programming challenge – Narcissistic Numbers

Comments 6

  1. walter

    there is a small bug in narc function, as it includes 7 in the final sum (due to 0=0 in til[n]=not[o<10 … could just fix by dropping, final statement being sum o 1_where til[n]=not[o<10]*o)

  2. Jose Cambronero

    Here’s a (probably) naive solution, where you string digits and parse as separate numbers

    sum n where n=sum each (“I”$”s) xexp’ count each s:string n:10+til 1+(`int$2e6)-10

  3. Akash

    \ts {power:count each sn:string nn:1+9_til x;show nn where nn=sum each (xexp[-48+`int$sn;power])}[2000000]
    2723j, 450785888j

    around 2.7 seconds

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax