euler/ipython/EulerProblem006.ipynb

95 lines
2.1 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Euler Problem 6\n",
"\n",
"The sum of the squares of the first ten natural numbers is,\n",
"\n",
"$1^2 + 2^2 + ... + 10^2 = 385$\n",
"\n",
"The square of the sum of the first ten natural numbers is,\n",
"\n",
"$(1 + 2 + ... + 10)^2 = 55^2 = 3025$\n",
"\n",
"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$.\n",
"\n",
"Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Okay, this is as straightforward as it can get."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"25164150\n"
]
}
],
"source": [
"s = sum([x for x in range(1, 101)])**2 - sum([x**2 for x in range(1, 101)])\n",
"assert(s == 25164150)\n",
"print(s)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"General solution."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"def diff_between_sum_of_squares_and_square_sum(n):\n",
" return sum([x for x in range(1, n + 1)])**2 - sum([x**2 for x in range(1, n + 1)])\n",
"\n",
"assert(diff_between_sum_of_squares_and_square_sum(100) == 25164150)\n",
"assert(diff_between_sum_of_squares_and_square_sum(10) == 2640)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.4"
}
},
"nbformat": 4,
"nbformat_minor": 0
}