0
0

[Python][Julia]project euler 12 (プロジェクトオイラー12)

Last updated at Posted at 2023-12-21

Projevt Euler Ploblem 12 (プロジェクトオイラー12)

Highly Divisible Triangular Number

Project Euler 12を解いたので、備忘のために残しておく。
Python と Julia のコードを両方かいた(下段)
処理速度はJuliaの方がずっと速い。

自分のPCだと
Pythonが 約2.5秒
Julia が 約1.5秒
だった。

問題

問題文(適当な和訳なので、完全に正しいかはわからない...)
三角数の数列は自然数の足していくことによってできる。
7番目の三角数は1 + 2 + 3 + 4 + 5 + 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
28は約数の数が5個を超える最初の三角数だとわかる。
約数の数が500個を超える最初の三角数の値は?

答え:76576500

問題文(原文)
The sequence of triangle numbers is generated by adding the natural numbers.
So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 7 = 28
The first ten terms would be:1,3,6,10,15,21,28,36,45,55....

Let us list the factors of the first seven triangle numbers:
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

We can see that 28 is the first triangle number to have over five divisors.
What is the value of the first triangle number to have over five hundred divisors?

求め方の方針

約数を求める関数(divisors) を作り
三角数の値を約数を求める関数の引数として、約数の個数が500を超えるまで三角数の1番目から計算(seek_answer)。
三角数の和は

\sum_{k=1}^{n} k = 1 + 2 + 3 + \cdots + n = \frac{n(n+1)}{2} \

から

Python のコード

Ploblem12(Python)
import time #処理時間計測用
start = time.time() 
 
def divisors(num: int) -> int:
    count: int = 0
    for i in range(1, int(num**0.5) + 1):
        if num % i == 0:
            count += 1
            if num // i != i:
                count += 1
    return count

def seek_answer(d: int) -> int:
    ans: int = 1
    k: int = 1
    while divisors(ans) < d:
        ans = k*(k + 1)//2
        k += 1    
    return ans

d = 500
print(seek_answer(d))

end = time.time()
 
print(f"処理時時間:{end - start}")

Juliaのコード

Ploblem12(Julia)
using Dates #処理時間計測用

start = Dates.now()

function divisors(num::Int64)::Int64
    count::Int64 = 0
    for i in 1:ceil(sqrt(num))
        if num % i == 0
            count += 1
            if num ÷ i != i
                count += 1
            end
        end
    end
    return count
end



function seek_answer(d::Int64)::Int64
    ans::Int64 = 1
    k::Int64 = 1
    while divisors(ans) < d
        ans = k*(k+1)/2
        k += 1
    end
    return ans
end

d::Int64 = 500
println(seek_answer(d))
endtime = now()
println("処理時間:", endtime - start)

2023/12/24 コードを修正しました(ありがとうございます!)

0
0
2

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