2762a8417f1688162c895faaccd60d2d79723fd8
[project-euler.git] / euler44.ipynb
1 {
2 "cells": [
3 {
4 "cell_type": "code",
5 "execution_count": 2,
6 "metadata": {
7 "collapsed": false
8 },
9 "outputs": [
10 {
11 "data": {
12 "text/plain": [
13 ":pentagonal"
14 ]
15 },
16 "execution_count": 2,
17 "metadata": {},
18 "output_type": "execute_result"
19 }
20 ],
21 "source": [
22 "def pentagonal(n)\n",
23 " n * (3 * n - 1) / 2\n",
24 "end"
25 ]
26 },
27 {
28 "cell_type": "code",
29 "execution_count": 22,
30 "metadata": {
31 "collapsed": false
32 },
33 "outputs": [
34 {
35 "name": "stdout",
36 "output_type": "stream",
37 "text": [
38 "2167, 1020 -> 5482660\n",
39 "2167, 1020 -> 5482660\n"
40 ]
41 }
42 ],
43 "source": [
44 "pentagonals = Set.new()\n",
45 "\n",
46 "found = false\n",
47 "sum_index = 1\n",
48 "best_k = 0\n",
49 "best_j = 0\n",
50 "best_diff = pentagonal(5000)\n",
51 "\n",
52 "while !found do\n",
53 " pentagonals << pentagonal(sum_index)\n",
54 " ((sum_index/2)...sum_index).each do |j|\n",
55 " k = sum_index - j\n",
56 " diff = pentagonal(j) - pentagonal(k)\n",
57 " if pentagonals.include?(diff) && pentagonals.include?(pentagonal(j)+pentagonal(k))\n",
58 " found = true\n",
59 " puts \"#{j}, #{k} -> #{diff}\"\n",
60 " if diff < best_diff\n",
61 " best_diff = diff\n",
62 " best_k = k\n",
63 " best_j = j\n",
64 " end\n",
65 " end\n",
66 " end\n",
67 " sum_index += 1\n",
68 "end\n",
69 "puts \"#{best_j}, #{best_k} -> #{best_diff}\""
70 ]
71 },
72 {
73 "cell_type": "code",
74 "execution_count": 18,
75 "metadata": {
76 "collapsed": false
77 },
78 "outputs": [
79 {
80 "data": {
81 "text/plain": [
82 "true"
83 ]
84 },
85 "execution_count": 18,
86 "metadata": {},
87 "output_type": "execute_result"
88 }
89 ],
90 "source": [
91 "pentagonals.include?(pentagonal(2167))"
92 ]
93 },
94 {
95 "cell_type": "code",
96 "execution_count": 23,
97 "metadata": {
98 "collapsed": false
99 },
100 "outputs": [
101 {
102 "data": {
103 "text/plain": [
104 "210"
105 ]
106 },
107 "execution_count": 23,
108 "metadata": {},
109 "output_type": "execute_result"
110 }
111 ],
112 "source": [
113 "pentagonal(12)"
114 ]
115 },
116 {
117 "cell_type": "code",
118 "execution_count": null,
119 "metadata": {
120 "collapsed": true
121 },
122 "outputs": [],
123 "source": []
124 }
125 ],
126 "metadata": {
127 "kernelspec": {
128 "display_name": "Ruby 2.4.0",
129 "language": "ruby",
130 "name": "ruby"
131 },
132 "language_info": {
133 "file_extension": ".rb",
134 "mimetype": "application/x-ruby",
135 "name": "ruby",
136 "version": "2.4.0"
137 }
138 },
139 "nbformat": 4,
140 "nbformat_minor": 0
141 }