Files
euler-project/problems/014_problem/014_problem_jnotebook.ipynb
2020-08-02 21:06:44 -04:00

146 lines
3.4 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Problem 14:\n",
"\n",
"[Euler Project #14](https://projecteuler.net/problem=14)\n",
"\n",
"\n",
"\n",
"> The following iterative sequence is defined for the set of positive integers:\n",
"> \n",
"> n → n/2 (n is even)\n",
"> n → 3n + 1 (n is odd)\n",
"> \n",
"> Using the rule above and starting with 13, we generate the following sequence:\n",
"> 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1\n",
"> \n",
"> It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.\n",
"> \n",
"> Which starting number, under one million, produces the longest chain?\n",
"> \n",
"> NOTE: Once the chain starts the terms are allowed to go above one million.\n",
"\n",
"\n",
"---"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Reserved Space For Imports\n",
"---"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import os"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Reserved Space For Method Definition\n",
"---"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"def collatz_length(n: int):\n",
" count=0\n",
" while n != 1:\n",
" if n%2 == 0:\n",
" n=int(n/2)\n",
" count+=1\n",
" else:\n",
" n=int(3*n+1)\n",
" count+=1\n",
" return int(count+1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### I can't think of a way to simplify the problem, so brute force then???"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"tags": []
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": "The longest sequence was 525 members long, with a starting number of 837798\n"
}
],
"source": [
"# initialize a dictionary for storage\n",
"solution_dict = {\n",
" 'candidate': 1,\n",
" 'length': 1\n",
"}\n",
"\n",
"for i in range(1000000):\n",
" length=collatz_length(i+1)\n",
" if length > solution_dict['length']:\n",
" solution_dict['candidate']=i\n",
" solution_dict['length']=length\n",
"\n",
"print(\"The longest sequence was \",solution_dict['length'],\" members long, with a starting number of \",solution_dict['candidate']) "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"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.8.3"
}
},
"nbformat": 4,
"nbformat_minor": 4
}