-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path3-example.py
executable file
·87 lines (70 loc) · 2.09 KB
/
3-example.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#!/usr/bin/env python
# 3-example
# A simple demonstration script to find the largest prime number
# below a given limit.
#
# This file is intentionally inefficient in order to demonstrate
# various ways to time execution
#
# Usage:
# python 3-example.py 10000
#
# Author: Allen Leis <al1075@georgetown.edu>
# Created: Wed Sep 13 21:50:05 2015 -0400
#
# Copyright (C) 2015 georgetown.edu
# For license information, see LICENSE.txt
#
# ID: 3-example.py [] al1075@georgetown.edu $
"""
A simple demonstration script to find the largest prime number
below a given limit.
"""
##########################################################################
## Imports
##########################################################################
import sys
import time
##########################################################################
## Code
##########################################################################
class Timer(object):
"""
Basic timer class to use as a context manager.
https://www.python.org/dev/peps/pep-0343/
"""
def __enter__(self):
self.start = time.time()
return self
def __exit__(self, *args):
self.end = time.time()
self.secs = self.end - self.start
def is_prime(limit):
"""
Using the most time intensive method possible, return True or False
as to whether the supplied number is prime
"""
for number in range(2,limit):
if (limit % number) == 0:
return False
return True
def find_largest_prime(limit):
"""
Find the highest number below the supplied limit/upper bound
that is a prime number
"""
i = 2
largest_prime = None
while i < limit:
if is_prime(i):
largest_prime = i
i += 1
return largest_prime
##########################################################################
## Execution
##########################################################################
if __name__ == '__main__':
upper_bound = int(sys.argv[1])
with Timer() as t:
print find_largest_prime(upper_bound)
print 'elapsed time: %0.2fs' % t.secs