eulerbooks/notebooks/problem0055.ipynb

110 lines
2.6 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"id": "de629cc8",
"metadata": {},
"source": [
"# [Lychrel Numbers](https://projecteuler.net/problem=55)\n",
"\n",
"This could get tricky if we were working with fixed size integers, since the reverse-and-add process for [Lychrel numbers](https://en.wikipedia.org/wiki/Lychrel_number) can result in some big numbers. But Python ints have unlimited precision, so no need to worry about that."
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "5588d5d2",
"metadata": {},
"outputs": [],
"source": [
"def is_palindrome(n):\n",
" s = str(n)\n",
" return s == s[::-1]\n",
"\n",
"\n",
"def is_lychrel_number(n):\n",
" for _ in range(0, 50):\n",
" rev = int(str(n)[::-1])\n",
" n += rev\n",
" if is_palindrome(n):\n",
" return False\n",
" \n",
" return True"
]
},
{
"cell_type": "markdown",
"id": "d45f3460",
"metadata": {},
"source": [
"This is easy to brute force, since we're not checking that many numbers, and we loop at most 50 times in our test."
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "e473996a",
"metadata": {},
"outputs": [],
"source": [
"lychrel_numbers = {n for n in range(1, 10000) if is_lychrel_number(n)}"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "2c3f1cbf",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"249"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"len(lychrel_numbers)"
]
},
{
"cell_type": "markdown",
"id": "ef8a3b03",
"metadata": {},
"source": [
"## Relevant sequences\n",
"* Suspected Lychrel numbers: [A023108](https://oeis.org/A023108)\n",
"\n",
"#### Copyright (C) 2025 filifa\n",
"\n",
"This work is licensed under the [Creative Commons Attribution-ShareAlike 4.0 International license](https://creativecommons.org/licenses/by-sa/4.0/) and the [BSD Zero Clause license](https://spdx.org/licenses/0BSD.html)."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "SageMath 9.5",
"language": "sage",
"name": "sagemath"
},
"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.11.2"
}
},
"nbformat": 4,
"nbformat_minor": 5
}