Multiples of 3 and 5, Project Euler Problem 1

Multiples of 3 and 5, Project Euler Problem 1

February 18, 2020
Project Euler
Project Euler, Python

https://projecteuler.net/problem=1

1000より小さい3の倍数と5の倍数を全て足せという問題。数学的アプローチなら等差数列の和の公式を使えばよさそう。ただし両方の和を単純に足すと3×5=15の倍数分が重複するので注意。

Pythonの勉強も兼ねるのでまずはloop文書いて愚直に足し込んでみる。とりあえずfor文どうやって書くんだっけ?でドキュメント眺めるところからスタート(Pythonistaは公式ドキュメントにすぐアクセスできるのでエラい!)。An Informal Introduction 眺めてるとrange関数を使えば簡単そう!ってことで書いてみる。

Solution 1 #

# https://projecteuler.net/problem=1

sum = 0
for n in range(3, 1000, 3):
  sum += n
for n in range(5, 1000, 5):
  if n % 3 != 0:
    sum += n
print(sum)

Solution 2 #

等差数列の和の公式Ver.

# https://projecteuler.net/problem=1

def sum_multiples(diff, limit = 999):
	# n * (p(1) + p(n)) / 2
	nth_num = limit - limit % diff
	n = nth_num // diff
	return n * (diff + nth_num) // 2
		
result = sum_multiples(3) + sum_multiples(5) - sum_multiples(15)
print(result) 

今日の学び(Python) #

  • 四則演算は +-*/
  • int 同士の +-* は int を返すが / は float
  • int を返す除算は //
  • 剰余演算は %
  • 乗数は **
  • for, while, if 文の末尾に : コロン必要
  • 関数定義 def 文の末尾にも : コロン必要