LoginSignup
0
0

More than 3 years have passed since last update.

Project Euler 016, 020を解いてみる。「各位の数字の和」

Last updated at Posted at 2019-09-14

Project Euler 016, 020

016

215 = 32768 であり, 各位の数字の和は 3 + 2 + 7 + 6 + 8 = 26 となる.
同様にして, 21000 の各位の数字の和を求めよ.

020

n × (n - 1) × ... × 3 × 2 × 1 を n! と表す.
例えば, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800 となる.
この数の各桁の合計は 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27 である.
では, 100! の各位の数字の和を求めよ.

->次の問題

考え方

016と020は類似の問題なので合わせて解きます。
桁数や第1桁、最高位の数字を出す方法はありますが、各位の数字は実際に計算する以外の方法が思いつかなかったので、単純に計算しています。
pythonはstrにすることで各桁の数字を文字列で取り出せるので便利ですね。

コード

euler016.py
def main016():
    number = 2 ** 1000
    num_list = [int(i) for i in str(number)]
    print(sum(num_list))


def main020():
    number = 1
    for i in range(2, 101):
        number *= i
    num_list = [int(i) for i in str(number)]
    print(sum(num_list))


if __name__ == '__main__':
    from time import time as t
    start = t()
    main016()
    print(t() - start)
    start = t()
    main020()
    print(t() - start)

paizaにて実行
結果
1366
6.604194641113281e-05
648
3.266334533691406e-05

シンプルな問題が続きますね

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0