LoginSignup
2
2

More than 5 years have passed since last update.

Python で Project Euler #12「高度整除三角数」

Posted at

Problem 12 「高度整除三角数」

三角数の数列は自然数の和で表わされ, 7番目の三角数は 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28 である. 三角数の最初の10項は:

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

となる.
最初の7項について, その約数を列挙すると, 以下のとおり.

 1: 1
 3: 1,3
 6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28

これから, 7番目の三角数である28は, 5個より多く約数をもつ最初の三角数であることが分かる.
では, 500個より多く約数をもつ最初の三角数はいくつか.

Python
import math

# limit = 5
limit = 500

def compute_factors(num):
  factors = [1]
  if(num == 1): return factors
  for i in range(2, int(math.floor(math.sqrt(num))) + 1):
    if(num % i == 0):
      factors.append(i)
  factors_rev = list(factors)
  factors_rev.reverse()
  for i in factors_rev:
    fac = num // i
    if(fac not in factors):
      factors.append(fac)
  return factors

triangular_nums = [1]
factors = []
n = 2
while True:
  triangular_num = triangular_nums[n-1-1] + n
  triangular_nums.append(triangular_num)
  factors = compute_factors(triangular_num)
  if(len(factors) > limit):
    break
  n += 1

result = triangular_nums[-1]

print result
print result == 76576500
print n
print factors[:10]
結果
76576500
True
12375
[1, 2, 3, 4, 5, 6, 7, 9, 10, 11]
2
2
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
2
2