0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Python][Julia]Project euler6 (プロジェクトオイラー6)

Posted at

Project euler Ploblem 6 (プロジェクトオイラー6)

Sum Square Difference

備忘のために残しておく。
この問題は、手計算可能でコードを書く必要がなかった。
(一応、コードは載せている)

問題

問題文 (意訳)

100までの自然数の和の2乗と自然数の2乗の和の差を求めよ

原文

The sum of the squares of the first ten natural numbers is,

\begin{align}
1^2 + 2^2 + ... + 10^2 = 385
\end{align}

The square of the sum of the first ten natural numbers is,

\begin{align}
(1 + 2 + ... + 10)^2 = 55^2 = 3025
\end{align}

Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is
3025 - 385 = 2640.

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

答え

25164150

解答の方針

1個目の解答方針

\begin{align}
1^2 + 2^2 + ... + n^2 &= \frac{1}{6}n(n+1)(2n+1)\ \\
(1 + 2 + ... + n)^2 &= \bigl(\frac{1}{2}n(n+1)\bigr)^2\ \\

\end{align}

を使って
以下のように式変形し、手で計算する。

\begin{align}

(1 + 2 + ... + n)^2  - (1^2 + 2^2 + ... + n^2) \\
\end{align}
\begin{align}
&=(\frac{1}{2}n(n+1))^2\ -\frac{1}{6}n(n+1)(2n+1)\\
&= n(n+1)(\frac{1}{4}n(n+1) - \frac{1}{6}(2n+1)) \\
&= \frac{1}{12}(n-1)n(n+1)(3n+2) \\
\end{align}

100の場合だと 99×100×101×302÷12 となって手で計算できる

2個目の解答方針

単純に計算する

Pythonのコード

Python Ploblem6
def sum_of_squares(limit: int) -> int:
    sum: int = 0
    for i in range(limit + 1):
       sum +=  i**2
    return sum
def sum_squared(limit: int) -> int:
    sum: int = 0
    for i in range(limit + 1):
        sum += i
    return sum**2

print(sum_squared(100)-sum_of_squares(100))

Juliaのコード

Julia Ploblem6
function sum_of_squares(limit::Int64)::Int64
    sum::Int64 = 0
    for i in 1:limit
       sum +=  i^2
    end
    return sum
end

function sum_squared(limit::Int64)::Int64
    sum::Int64 = 0
    for i in 1:limit
        sum += i
    end
    return sum^2
end

println(sum_squared(100)-sum_of_squares(100))
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?