Skip to content

Instantly share code, notes, and snippets.

@Gobayli
Created October 16, 2017 05:26
Show Gist options
  • Select an option

  • Save Gobayli/69e39dbdcb1717ba4dc6c8cbbd7b518a to your computer and use it in GitHub Desktop.

Select an option

Save Gobayli/69e39dbdcb1717ba4dc6c8cbbd7b518a to your computer and use it in GitHub Desktop.
Lesson 1 Lab: Prime factors solution
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Look for the largest prime number\n",
"##### The prime factors of 13195 are 5, 7, 13 and 29.\n",
"##### What is the largest prime factor of the number 600851475143?"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[5, 7, 13, 29]\n",
"29\n",
"[71, 839, 1471, 6857L]\n",
"6857\n"
]
}
],
"source": [
"\"\"\"\n",
"1.Create a function to get all factors of the number\n",
"2.In a for-loop of a for-loop in the number, loop in every factor to find their prime factor\n",
"3.Create a method or find an existing module that can replace the repeating for-loop of each factor -> Generato concept\n",
"4.Get the max of the results\n",
"\"\"\"\n",
"\n",
"def prime(n):\n",
" \"\"\"\n",
" To generate all prime factors of the number\n",
" \"\"\"\n",
" i = 2\n",
" while i * i <= n:\n",
" while not n % i:\n",
" yield i\n",
" n /= i\n",
" i += 1\n",
" if n > 1:\n",
" yield n\n",
"\n",
"# print prime(13195)\n",
"# print prime(600851475143)\n",
"\n",
"print list(prime(13195))\n",
"print max(prime(13195))\n",
"\n",
"print list(prime(600851475143))\n",
"print max(prime(600851475143))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Reference:\n",
"* https://wiki.python.org/moin/Generators\n",
"* https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/00138681965108490cb4c13182e472f8d87830f13be6e88000\n",
"* https://stackoverflow.com/questions/19157283/right-algorithm-for-finding-largest-prime-factor\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 2",
"language": "python",
"name": "python2"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.11"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment