euler/ipython/EulerProblem041.ipynb
2018-12-19 15:58:46 -05:00

124 lines
2.5 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Pandigital prime (Euler Problem 41)"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"[https://projecteuler.net/problem=41]\n",
"\n",
"We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime.\n",
"\n",
"What is the largest n-digit pandigital prime that exists?"
]
},
{
"cell_type": "code",
"execution_count": 49,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def expmod(base, exp, m):\n",
" if exp == 0:\n",
" return 1\n",
" if (exp % 2 == 0):\n",
" return (expmod(base, exp // 2, m) ** 2 % m)\n",
" return (base * expmod(base, exp - 1, m) % m)\n",
" \n",
"def expmod_naiv(base, exp, m):\n",
" return base ** exp % m\n",
"\n",
"def fermat_test(n):\n",
" a = n - 3\n",
" return expmod(a, n, n) == a"
]
},
{
"cell_type": "code",
"execution_count": 50,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"assert(expmod(2, 100000, 2143) == expmod_naiv(2, 100000, 2143))"
]
},
{
"cell_type": "code",
"execution_count": 51,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"assert(fermat_test(2143))"
]
},
{
"cell_type": "code",
"execution_count": 54,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"7652413\n"
]
}
],
"source": [
"import itertools\n",
"\n",
"for pandigital in itertools.permutations(\"7654321\"):\n",
" p = int(\"\".join(pandigital))\n",
" if fermat_test(p):\n",
" s = p\n",
" break\n",
" \n",
"print(s)\n",
"assert(s == 7652413)"
]
}
],
"metadata": {
"completion_date": "Wed, 19 Dec 2018, 20:14",
"kernelspec": {
"display_name": "Python 3",
"language": "python3.6",
"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.6.5"
},
"tags": [
"pandigital",
"prime",
"fermat",
"test"
]
},
"nbformat": 4,
"nbformat_minor": 2
}