Home
About
Resume
Projects
Links
Blog
Download notebook
{ "cells": [ { "cell_type": "markdown", "id": "b29f9b73-1d95-4918-a8f2-9a24ef96fefd", "metadata": {}, "source": [ "### Q14\n", "Which starting number, under one million, produces the longest chain?" ] }, { "cell_type": "code", "execution_count": 1, "id": "ea9d71c5-55b2-4b17-a08f-4e4e4d04a554", "metadata": {}, "outputs": [], "source": [ "def collatz_walker(num, collatz_map):\n", " if num in collatz_map:\n", " return collatz_map[num]\n", " elif num == 1:\n", " collatz_map[1] = 0\n", " return\n", " collatz_map[num] = collatz_walker(3*num+1 if num % 2 else num//2, collatz_map)+1\n", " return collatz_map[num]\n", " \n", "def get_collatz_map(max_value, exclude_end = True):\n", " collatz_map = {}\n", " if not exclude_end:\n", " max_value += 1\n", " for i in range(1,max_value):\n", " collatz_walker(i,collatz_map)\n", " return collatz_map\n", "\n", "def max_value_key(data_dict): \n", " return sorted(data_dict.items(),key= lambda x : x[1],reverse=True)[0][0]" ] }, { "cell_type": "code", "execution_count": 2, "id": "9949eaf2-04fd-4c02-980e-ef0096a79437", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "CPU times: user 1.34 s, sys: 68.9 ms, total: 1.41 s\n", "Wall time: 1.41 s\n" ] }, { "data": { "text/plain": [ "837799" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "%%time\n", "max_value_key(get_collatz_map(1000000))" ] }, { "cell_type": "code", "execution_count": null, "id": "bebcbba8-1bc5-471f-897f-b744ad7f6cd3", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.8.10" } }, "nbformat": 4, "nbformat_minor": 5 }
Previous Notebook:
Project Euler Q13
Next Notebook:
Project Euler Q15
Loading