Skip to content

Instantly share code, notes, and snippets.

@jakedobkin
Created December 2, 2011 21:35
Show Gist options
  • Select an option

  • Save jakedobkin/1424931 to your computer and use it in GitHub Desktop.

Select an option

Save jakedobkin/1424931 to your computer and use it in GitHub Desktop.
Euler 30
#!/usr/local/bin/node
/* the question is a little unclear- b/c a naive reading might assume
you only need to check the five digit numbers, since the example given is 4 digits
this would be a special class of numbers called "narcissistic"- but here we're looking
for a larger case- ANY number of digits that, when ^5 and added, give the number, starting
from two (since the problem says don't count 1). harder is to figure out upper limit.
at first, i just let it run to 1MM, hoping that would be enough. it was. then i read
up and found someone had figured out the exact limit with this logic:
assume each digit is a 9: 9^5~~ 60K-- so every digit we add gives us another 60K or so.
one digit- right side of equation is up to 60k
two digits- 120k
three digits- 180k
four digits- 240k
five digits- 300k
six digits- 360k
seven digits- 420K-- notice this is a lot less than 1M, which is the smallest seven digit number
-- so we only have to search up to 6 digits
-- and specifically, assuming all 6 digits were 9's, to 354294
*/
sum = 0;
for (i=1;i<=354294;i++)
{
test_number = i.toString();
if ((Math.pow(Number(test_number.charAt(0)),5)+Math.pow(Number(test_number.charAt(1)),5)+Math.pow(Number(test_number.charAt(2)),5)+Math.pow(Number(test_number.charAt(3)),5)+Math.pow(Number(test_number.charAt(4)),5)+Math.pow(Number(test_number.charAt(5)),5)) == i)
{
console.log(i + " is a narcissistic number");
sum +=i;
}
}
console.log("sum equals " + sum);
@jakedobkin
Copy link
Author


sum = 0

for i in range (2,354295):

# note you actually have to pad the number to get this to work for < 6 digits
    test_number = str(format(i,"06d"))
    if ( (int(test_number[0:1])**5)+(int(test_number[1:2])**5)+(int(test_number[2:3])**5)+(int(test_number[3:4])**5)+(int(test_number[4:5])**5)+(int(test_number[5:6])**5) == i):
        print i," is a narcissistic number"
        sum = sum + i
print "sum equals ", sum

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment