As mentioned by others, the main issue appears to be using range
instead of range
in Python 2.7. Using %timeit
, both functions are almost the same if one were to use xrange
(Python 2.7).
%timeit isPrimeRange(n)
100000 loops, best of 3: 15.2 µs per loop
%timeit isPrimeWhile(n)
100000 loops, best of 3: 15.8 µs per loop
%load_ext line_profiler
%load_ext memory_profiler
from isPrimeRange import isPrimeRange
from isPrimeWhile import isPrimeWhile
n = 353591872901
isPrimeRange: Line Profiler
%lprun -f isPrimeRange isPrimeRange(n)
Timer unit: 1e-06 s
**Total time: 5.5e-05 s**
File: isPrimeRange.py
Function: isPrimeRange at line 1
Line # Hits Time Per Hit % Time Line Contents
==============================================================
1 def isPrimeRange(n):
2 82 25 0.3 45.5 for i in xrange(2,n/2+1):
3 82 29 0.4 52.7 if(n%i == 0):
4 1 1 1.0 1.8 return i
5 return n
isPrimeWhile: Line Profiler
%lprun -f isPrimeWhile isPrimeWhile(n)
Timer unit: 1e-06 s
**Total time: 9e-05 s**
File: isPrimeWhile.py
Function: isPrimeWhile at line 3
Line # Hits Time Per Hit % Time Line Contents
==============================================================
3 def isPrimeWhile(n):
4 1 1 1.0 1.1 i = 2
5 82 34 0.4 37.8 while(i <= n/2+1):
6 82 31 0.4 34.4 if(n%i == 0):
7 1 0 0.0 0.0 return i
8 81 24 0.3 26.7 i += 1
9 return n
Using iPython's memory profiler, you can see that both use the same amount of memory.
isPrimeRange: Memory Profiler
%mprun -f isPrimeRange isPrimeRange(n)
('',)
Filename: isPrimeRange.py
Line # Mem usage Increment Line Contents
================================================
1 24.2 MiB 0.0 MiB def isPrimeRange(n):
2 24.2 MiB 0.0 MiB for i in xrange(2,n/2+1):
3 24.2 MiB 0.0 MiB if(n%i == 0):
4 24.2 MiB 0.0 MiB return i
5 return n
isPrimeWhile: Memory Profiler
%mprun -f isPrimeWhile isPrimeWhile(n)
('',)
Filename: isPrimeWhile.py
Line # Mem usage Increment Line Contents
================================================
3 24.2 MiB 0.0 MiB def isPrimeWhile(n):
4 24.2 MiB 0.0 MiB i = 2
5 24.2 MiB 0.0 MiB while(i <= n/2+1):
6 24.2 MiB 0.0 MiB if(n%i == 0):
7 24.2 MiB 0.0 MiB return i
8 24.2 MiB 0.0 MiB i += 1
9 return n