Problem30

30分プログラム、その303。Problem30 via Project Euler

驚くべきことに, 各桁を4乗した和が元の数と一致する数は3つしかない.

  • 1634 = 1^4 + 6^4 + 3^4 + 4^4
  • 8208 = 8^4 + 2^4 + 0^4 + 8^4
  • 9474 = 9^4 + 4^4 + 7^4 + 4^4

ただし, 1=1^4は含まないものとする. この数たちの和は 1634 + 8208 + 9474 = 19316 である.
各桁を5乗した和が元の数と一致するような数の総和を求めよ.

全然解ける気がしなかったけど、id:selvaggio:20080512のおかげで解けたよ。ありがとうっ!

使い方

$ time python problem30.py
4150
4151
54748
92727
93084
194979
answer 443839
python problem30.py  18.50s user 0.24s system 90% cpu 20.727 total

ソースコード

#! /usr/bin/python
# -*- mode:python; coding:utf-8 -*-
#
# problem30.py -
#
# Copyright(C) 2008 by mzp
# Author: MIZUNO Hiroki / mzpppp at gmail dot com
# http://howdyworld.org
#
# Timestamp: 2008/05/13 22:40:05
#
# This program is free software; you can redistribute it and/or
# modify it under MIT Lincence.
#

def split(n):
    if n < 10:
        return [n]
    else:
        q = n / 10
        r = n % 10
        xs = split(q)
        return xs+[r]

def satisfy(n):
    return n == sum(map(lambda x : x**5,split(n)))

def main():
    xs = []
    for n in xrange(10,int(1e6)):
        if satisfy(n):
            xs.append(n)
            print n
    print "answer",sum(xs)

if __name__ == '__main__':
    main()