Skip to content

Instantly share code, notes, and snippets.

@mburke05
Created November 6, 2015 19:05
Show Gist options
  • Save mburke05/d956fe61958056976447 to your computer and use it in GitHub Desktop.
Save mburke05/d956fe61958056976447 to your computer and use it in GitHub Desktop.
{
"cells": [
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"from math import floor, sqrt"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"### Assignment ###\n",
"#\n",
"# Your assignment is to implement the\n",
"# following function: `find_next_prime`.\n",
"# As the name states, given the number `n` the \n",
"# function should return the next closest prime.\n",
"#\n",
"# Examples:\n",
"# * `find_next_prime(6)` should return 7.\n",
"# * `find_next_prime(10)` should return 11.\n",
"# * `find_next_prime(11)` should return 13.\n",
"#\n",
"# You can use whatever you want (data structures,\n",
"# language features, etc).\n",
"# \n",
"# Unit tests would be a plus.\n",
"#\n",
"### End Assignment ###\n",
" \n",
"def find_next_prime(n):\n",
" i = n+1\n",
" while True:\n",
" if is_prime(i):\n",
" return i\n",
" i+=1 "
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def is_prime(n): \n",
" for i in xrange(2,int(floor(sqrt(n)))+1):\n",
" if not n % i:\n",
" return False\n",
" return True"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"%%timeit\n",
"is_prime(7)\n",
"is_prime(11)\n",
"is_prime(13)"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"10000 loops, best of 3: 36.9 µs per loop\n"
]
}
],
"source": [
"%%timeit\n",
"[find_next_prime(6),\n",
"find_next_prime(10),\n",
"find_next_prime(11),\n",
"find_next_prime(200),\n",
"find_next_prime(2000),\n",
"find_next_prime(200000)]"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[7, 11, 13, 211, 2003, 200003]"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"[find_next_prime(6),\n",
"find_next_prime(10),\n",
"find_next_prime(11),\n",
"find_next_prime(200),\n",
"find_next_prime(2000),\n",
"find_next_prime(200000)]"
]
}
],
"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.9"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment