Departement Informatik
Basics of CS
Complexity and Primality Testing
Hans-Joachim Böckenhauer Dennis Komm
Functions
Scope and Lifetime of Variables
Local Variables
Parameters of a function are only valid within this function
def f(x):
return x + 5 print(x)
NameError: name ’x’ is not defined
Local Variables
Parameters of a function are only valid within this function
def f(x):
return x + 5 print(x)
NameError: name ’x’ is not defined
Local Variables
The same is true for variables that are defined in a function
def f(x):
y = 5
return x + y print(y)
NameError: name ’y’ is not defined
Local Variables
The same is true for variables that are defined in a function
def f(x):
y = 5
return x + y print(y)
NameError: name ’y’ is not defined
Local Variables
Such variables (parameters) are calledlocal variables
Variables defined outside of a function are calledglobal variables Field of validity is calledscopeof the variable
Time in which it is defined is calledlifetimeof the variable
def f(x): if x < 0:
return -100 y = x + 1 if y < 10:
y += 10 else:
y -= 20 return y
def f(x): if x < 0:
return-100 y = x + 1 if y < 10:
y += 10 else:
y -= 20 return y
Local Variables
Such variables (parameters) are calledlocal variables
Variables defined outside of a function are calledglobal variables Field of validity is calledscopeof the variable
Time in which it is defined is calledlifetimeof the variable
def f(x):
if x < 0:
return -100 y = x + 1 if y < 10:
y += 10 else:
y -= 20 return y
def f(x): if x < 0:
return-100 y = x + 1 if y < 10:
y += 10 else:
y -= 20 return y
Local Variables
Such variables (parameters) are calledlocal variables
Variables defined outside of a function are calledglobal variables Field of validity is calledscopeof the variable
Time in which it is defined is calledlifetimeof the variable
def f(x):
if x < 0:
return -100 y = x + 1 if y < 10:
y += 10 else:
y -= 20 return y
scopeofx
def f(x): if x < 0:
return-100 y = x + 1 if y < 10:
y += 10 else:
y -= 20 return y
Local Variables
Such variables (parameters) are calledlocal variables
Variables defined outside of a function are calledglobal variables Field of validity is calledscopeof the variable
Time in which it is defined is calledlifetimeof the variable
def f(x):
if x < 0:
return -100 y = x + 1 if y < 10:
y += 10 else:
y -= 20 return y
scopeofx
def f(x):
if x < 0:
return -100 y = x + 1 if y < 10:
y += 10 else:
y -= 20 return y
Local Variables
Such variables (parameters) are calledlocal variables
Variables defined outside of a function are calledglobal variables Field of validity is calledscopeof the variable
Time in which it is defined is calledlifetimeof the variable
def f(x):
if x < 0:
return -100 y = x + 1 if y < 10:
y += 10 else:
y -= 20 return y
scopeofx
def f(x):
if x < 0:
return -100 y = x + 1 if y < 10:
y += 10 else:
y -= 20 return y
scopeofy
Global Variables
Global variables can be accessed within a function
x = 1
def f(): y = x + 1 print(y) return print(x) f() print(x)
x = 1
def f(y): z = x + y return z print(x) print(f(2)) print(x)
Global Variables
Global variables can be accessed within a function
x = 1
def f():
y = x + 1 print(y) return print(x) f() print(x)
x = 1
def f(y): z = x + y return z print(x) print(f(2)) print(x)
Global Variables
Global variables can be accessed within a function
x = 1
def f():
y = x + 1 print(y) return print(x) f() print(x)
global variablex
x = 1
def f(y): z = x + y return z print(x) print(f(2)) print(x)
Global Variables
Global variables can be accessed within a function
x = 1
def f():
y = x + 1 print(y) return print(x) f() print(x)
local variableygets value
which depends on global variablex
x = 1
def f(y): z = x + y return z print(x) print(f(2)) print(x)
Global Variables
Global variables can be accessed within a function
x = 1
def f():
y = x + 1 print(y) return print(x) f() print(x)
output global variablex
x = 1
def f(y): z = x + y return z print(x) print(f(2)) print(x)
Global Variables
Global variables can be accessed within a function
x = 1
def f():
y = x + 1 print(y) return print(x) f() print(x)
output global variablex output local variabley
x = 1
def f(y): z = x + y return z print(x) print(f(2)) print(x)
Global Variables
Global variables can be accessed within a function
x = 1
def f():
y = x + 1 print(y) return print(x) f() print(x)
output global variablex output local variabley output global variablex
x = 1
def f(y): z = x + y return z print(x) print(f(2)) print(x)
Global Variables
Global variables can be accessed within a function
x = 1
def f():
y = x + 1 print(y) return print(x) f() print(x)
x = 1
def f(y):
z = x + y return z print(x) print(f(2)) print(x)
Global Variables
Global variables can be accessed within a function
x = 1
def f():
y = x + 1 print(y) return print(x) f() print(x)
x = 1
def f(y):
z = x + y return z print(x) print(f(2)) print(x)
global variablex
Global Variables
Global variables can be accessed within a function
x = 1
def f():
y = x + 1 print(y) return print(x) f() print(x)
x = 1
def f(y):
z = x + y return z print(x) print(f(2)) print(x)
parametery
Global Variables
Global variables can be accessed within a function
x = 1
def f():
y = x + 1 print(y) return print(x) f() print(x)
x = 1
def f(y):
z = x + y return z print(x) print(f(2)) print(x)
local variablezgets value
that depends on global variablex and parametery
Global Variables
Global variables can be accessed within a function
x = 1
def f():
y = x + 1 print(y) return print(x) f() print(x)
x = 1
def f(y):
z = x + y return z print(x) print(f(2)) print(x)
output global variablex
Global Variables
Global variables can be accessed within a function
x = 1
def f():
y = x + 1 print(y) return print(x) f() print(x)
x = 1
def f(y):
z = x + y return z print(x) print(f(2)) print(x)
output global variablex output local variablez
Global Variables
Global variables can be accessed within a function
x = 1
def f():
y = x + 1 print(y) return print(x) f() print(x)
x = 1
def f(y):
z = x + y return z print(x) print(f(2)) print(x)
output global variablex output local variablez output global variablex
Local Variables
Local and global variables can have the same name
Shadowing
Not forbidden, but should be avoided here whenever possible
x = 1
def f(): x = 2 return x print(x) print(f()) print(x)
x = 1
def f(x): x = x + 1 return x print(x) print(f(2)) print(x)
Local Variables
Local and global variables can have the same name Shadowing
Not forbidden, but should be avoided here whenever possible
x = 1
def f(): x = 2 return x print(x) print(f()) print(x)
x = 1
def f(x): x = x + 1 return x print(x) print(f(2)) print(x)
Local Variables
Local and global variables can have the same name Shadowing
Not forbidden, but should be avoided here whenever possible
x = 1
def f():
x = 2 return x print(x) print(f()) print(x)
x = 1
def f(x): x = x + 1 return x print(x) print(f(2)) print(x)
Local Variables
Local and global variables can have the same name Shadowing
Not forbidden, but should be avoided here whenever possible
x = 1
def f():
x = 2 return x print(x) print(f()) print(x)
global variablex
x = 1
def f(x): x = x + 1 return x print(x) print(f(2)) print(x)
Local Variables
Local and global variables can have the same name Shadowing
Not forbidden, but should be avoided here whenever possible
x = 1
def f():
x = 2 return x print(x) print(f()) print(x)
local variablex
x = 1
def f(x): x = x + 1 return x print(x) print(f(2)) print(x)
Local Variables
Local and global variables can have the same name Shadowing
Not forbidden, but should be avoided here whenever possible
x = 1
def f():
x = 2 return x print(x) print(f()) print(x)
local variablexis returned
x = 1
def f(x): x = x + 1 return x print(x) print(f(2)) print(x)
Local Variables
Local and global variables can have the same name Shadowing
Not forbidden, but should be avoided here whenever possible
x = 1
def f():
x = 2 return x print(x) print(f()) print(x)
output global variablex
x = 1
def f(x): x = x + 1 return x print(x) print(f(2)) print(x)
Local Variables
Local and global variables can have the same name Shadowing
Not forbidden, but should be avoided here whenever possible
x = 1
def f():
x = 2 return x print(x) print(f()) print(x)
output global variablex output local variablex
x = 1
def f(x): x = x + 1 return x print(x) print(f(2)) print(x)
Local Variables
Local and global variables can have the same name Shadowing
Not forbidden, but should be avoided here whenever possible
x = 1
def f():
x = 2 return x print(x) print(f()) print(x)
output global variablex output local variablex output global variablex
x = 1
def f(x): x = x + 1 return x print(x) print(f(2)) print(x)
Local Variables
Local and global variables can have the same name Shadowing
Not forbidden, but should be avoided here whenever possible
x = 1
def f():
x = 2 return x print(x) print(f()) print(x)
x = 1
def f(x):
x = x + 1 return x print(x) print(f(2)) print(x)
Local Variables
Local and global variables can have the same name Shadowing
Not forbidden, but should be avoided here whenever possible
x = 1
def f():
x = 2 return x print(x) print(f()) print(x)
x = 1
def f(x):
x = x + 1 return x print(x) print(f(2)) print(x)
global variablex
Local Variables
Local and global variables can have the same name Shadowing
Not forbidden, but should be avoided here whenever possible
x = 1
def f():
x = 2 return x print(x) print(f()) print(x)
x = 1
def f(x):
x = x + 1 return x print(x) print(f(2)) print(x)
parameterx
Local Variables
Local and global variables can have the same name Shadowing
Not forbidden, but should be avoided here whenever possible
x = 1
def f():
x = 2 return x print(x) print(f()) print(x)
x = 1
def f(x):
x = x + 1 return x print(x) print(f(2)) print(x)
parameterxgets new value that depends on its
current value
Local Variables
Local and global variables can have the same name Shadowing
Not forbidden, but should be avoided here whenever possible
x = 1
def f():
x = 2 return x print(x) print(f()) print(x)
x = 1
def f(x):
x = x + 1 return x print(x) print(f(2)) print(x)
parameterxis returned
Local Variables
Local and global variables can have the same name Shadowing
Not forbidden, but should be avoided here whenever possible
x = 1
def f():
x = 2 return x print(x) print(f()) print(x)
x = 1
def f(x):
x = x + 1 return x print(x) print(f(2)) print(x)
output global variablex
Local Variables
Local and global variables can have the same name Shadowing
Not forbidden, but should be avoided here whenever possible
x = 1
def f():
x = 2 return x print(x) print(f()) print(x)
x = 1
def f(x):
x = x + 1 return x print(x) print(f(2)) print(x)
output global variablex output parameterx
Local Variables
Local and global variables can have the same name Shadowing
Not forbidden, but should be avoided here whenever possible
x = 1
def f():
x = 2 return x print(x) print(f()) print(x)
x = 1
def f(x):
x = x + 1 return x print(x) print(f(2)) print(x)
output global variablex output parameterx output global variablex
Time Complexity of Algorithms
Primality Testing
Exercise – Primality Testing
Write a function that
takes an integerxas parameter
calculates whetherxis prime by search for a divisor between1andx
uses the%operator
depending on that either returnsTrue orFalse
Primality Test
def primetest(x):
if x < 2:
return False d = 2
while d < x:
if x % d == 0:
return False d += 1
return True
Primality Test
How long does it take the algorithm to produce the output?
What is itstime complexity?
This depends on the number of loop iterations An absolute value does not make sense here The loop is iterated (roughly)xtimes (ifxis prime) ï Time complexity grows withx
. . .but how fast?
Primality Test
How long does it take the algorithm to produce the output?
What is itstime complexity?
This depends on the number of loop iterations
An absolute value does not make sense here The loop is iterated (roughly)xtimes (ifxis prime) ï Time complexity grows withx
. . .but how fast?
Primality Test
How long does it take the algorithm to produce the output?
What is itstime complexity?
This depends on the number of loop iterations An absolute value does not make sense here The loop is iterated (roughly)xtimes (ifxis prime) ï Time complexity grows withx
. . .but how fast?
Primality Test
How long does it take the algorithm to produce the output?
What is itstime complexity?
This depends on the number of loop iterations An absolute value does not make sense here The loop is iterated (roughly)xtimes (ifxis prime) ï Time complexity grows withx. . .but how fast?
Time Complexity – Function of input size
We measure the time complexity as a function of the input size
The input of our algorithm is a single numberx In our computer, numbers are represented in binary Ignoring leading zeros, fornbits we obtain
2n−1 is10. . .00
| {z }
n
, 2n−1+ 1is10. . .01
| {z }
n
, . . . , and2n−1is11. . .11
| {z }
n
A number that is encoded withnbits has size around2n
Time Complexity – Function of input size
We measure the time complexity as a function of the input size The input of our algorithm is a single numberx
In our computer, numbers are represented in binary
Ignoring leading zeros, fornbits we obtain 2n−1 is10. . .00
| {z }
n
, 2n−1+ 1is10. . .01
| {z }
n
, . . . , and2n−1is11. . .11
| {z }
n
A number that is encoded withnbits has size around2n
Time Complexity – Function of input size
We measure the time complexity as a function of the input size The input of our algorithm is a single numberx
In our computer, numbers are represented in binary Ignoring leading zeros, fornbits we obtain
2n−1 is10. . .00
| {z }
n
, 2n−1+ 1is10. . .01
| {z }
n
, . . . , and2n−1is11. . .11
| {z }
n
A number that is encoded withnbits has size around2n
Time Complexity – Function of input size
We measure the time complexity as a function of the input size The input of our algorithm is a single numberx
In our computer, numbers are represented in binary Ignoring leading zeros, fornbits we obtain
2n−1 is10. . .00
| {z }
n
, 2n−1+ 1is10. . .01
| {z }
n
, . . . , and2n−1is11. . .11
| {z }
n
A number that is encoded withnbits has size around2n
Time Complexity – Technology Model
Random Access Machine
Execution model:Instructions are executed one after the other (on one processor core)
Memory model: Constant access time
Fundamental operations:Computations (+,−,·, . . .) comparisons, assignment / copy, flow control (jumps)
Unit cost model: Fundamental operations provide a cost of1
Time Complexity – Technology Model
Random Access Machine
Execution model:Instructions are executed one after the other (on one processor core)
Memory model: Constant access time
Fundamental operations:Computations (+,−,·, . . .) comparisons, assignment / copy, flow control (jumps)
Unit cost model: Fundamental operations provide a cost of1
Time Complexity – Technology Model
Random Access Machine
Execution model:Instructions are executed one after the other (on one processor core)
Memory model: Constant access time
Fundamental operations:Computations (+,−,·, . . .) comparisons, assignment / copy, flow control (jumps)
Unit cost model: Fundamental operations provide a cost of1
Time Complexity – Technology Model
Random Access Machine
Execution model:Instructions are executed one after the other (on one processor core)
Memory model: Constant access time
Fundamental operations:Computations (+,−,·, . . .) comparisons, assignment / copy, flow control (jumps)
Unit cost model: Fundamental operations provide a cost of1
Time Complexity – Note
We are not completely accurate here
Numbers can have arbitrarily large values
The time needed to add twon-bit numbers depends onn
Encoding of a floating point number does not directly correspond to its size Surely an addition is faster than a multiplication
Logarithmic cost modeltakes this into account, but is not used here We assume that arithmetic operations can be done in constant time
Time Complexity – Note
We are not completely accurate here
Numbers can have arbitrarily large values
The time needed to add twon-bit numbers depends onn
Encoding of a floating point number does not directly correspond to its size Surely an addition is faster than a multiplication
Logarithmic cost modeltakes this into account, but is not used here We assume that arithmetic operations can be done in constant time
Time Complexity – Note
We are not completely accurate here
Numbers can have arbitrarily large values
The time needed to add twon-bit numbers depends onn
Encoding of a floating point number does not directly correspond to its size Surely an addition is faster than a multiplication
Logarithmic cost modeltakes this into account, but is not used here We assume that arithmetic operations can be done in constant time
Time Complexity – Note
We are not completely accurate here
Numbers can have arbitrarily large values
The time needed to add twon-bit numbers depends onn
Encoding of a floating point number does not directly correspond to its size Surely an addition is faster than a multiplication
Logarithmic cost modeltakes this into account, but is not used here
We assume that arithmetic operations can be done in constant time
Time Complexity – Note
We are not completely accurate here
Numbers can have arbitrarily large values
The time needed to add twon-bit numbers depends onn
Encoding of a floating point number does not directly correspond to its size Surely an addition is faster than a multiplication
Logarithmic cost modeltakes this into account, but is not used here We assume that arithmetic operations can be done in constant time
Time Complexity of Our Primality Test
Supposexis a prime number, encoded usingnbits
Number of loop iterations grows with size ofx≈2n Loop is iterated around2ntimes
We would like to count thefundamental operations Algorithm executes five operations per iteration In total roughly5·2noperations
We would like to know how time complexity behaves whenn grows Ignore constant5
Time Complexity of Our Primality Test
Supposexis a prime number, encoded usingnbits Number of loop iterations grows with size ofx≈2n Loop is iterated around2ntimes
We would like to count thefundamental operations Algorithm executes five operations per iteration In total roughly5·2noperations
We would like to know how time complexity behaves whenn grows Ignore constant5
Time Complexity of Our Primality Test
Supposexis a prime number, encoded usingnbits Number of loop iterations grows with size ofx≈2n Loop is iterated around2ntimes
We would like to count thefundamental operations Algorithm executes five operations per iteration In total roughly5·2noperations
We would like to know how time complexity behaves whenn grows Ignore constant5
Time Complexity of Our Primality Test
Supposexis a prime number, encoded usingnbits Number of loop iterations grows with size ofx≈2n Loop is iterated around2ntimes
We would like to count thefundamental operations Algorithm executes five operations per iteration In total roughly5·2noperations
We would like to know how time complexity behaves whenn grows Ignore constant5
Time Complexity of Algorithms
Asymptotic Upper Bounds
Asymptotic Upper Bounds
The exact time complexity can usually not be predicted even for small inputs We are interested inupper bounds
We consider the asymptotic behavior of the algorithm And ignore all constant factors
Example
Linear growth with gradient5is as good as linear growth with gradient1 Quadratic growth with coefficient10is as good as quadratic growth with coefficient1
Asymptotic Upper Bounds
The exact time complexity can usually not be predicted even for small inputs We are interested inupper bounds
We consider the asymptotic behavior of the algorithm And ignore all constant factors
Example
Linear growth with gradient5is as good as linear growth with gradient1 Quadratic growth with coefficient10is as good as quadratic growth with coefficient1
Asymptotic Upper Bounds
Big-ONotation
The set O(2n) contains all functions that do not grow faster thanc·2nfor some constantc
The setO(g(n)) contains all functions f(n) that do not grow faster than c·g(n)for some constantc, wheref andg are positive
Use asymptotic notation to specify the time complexity of algorithms
We writeO(n2)and mean that the algorithm behaves for largen liken2: when the input length is doubled, the time taken multiplies by four (at most)
Asymptotic Upper Bounds
Big-ONotation
The set O(2n) contains all functions that do not grow faster thanc·2nfor some constantc
The set O(g(n)) contains all functions f(n) that do not grow faster than c·g(n)for some constantc, wheref andg are positive
Use asymptotic notation to specify the time complexity of algorithms
We writeO(n2)and mean that the algorithm behaves for largen liken2: when the input length is doubled, the time taken multiplies by four (at most)
Asymptotic Upper Bounds
Big-ONotation
The set O(2n) contains all functions that do not grow faster thanc·2nfor some constantc
The set O(g(n)) contains all functions f(n) that do not grow faster than c·g(n)for some constantc, wheref andg are positive
Use asymptotic notation to specify the time complexity of algorithms
We writeO(n2)and mean that the algorithm behaves for largenliken2: when the input length is doubled, the time taken multiplies by four (at most)
Asymptotic Upper Bounds – Illustration
g(n) =n2
n
Asymptotic Upper Bounds – Illustration
g(n) =n2 f(n)∈ O(g(n))
n0 n
Asymptotic Upper Bounds – Illustration
g(n) =n2 f(n)∈ O(g(n))
h(n)∈ O(g(n))
n0 n
Asymptotic Upper Bounds – Examples
O(g(n)) ={f:N→R+|es existierenc >0undn0∈N so dass für allen≥n0 gilt, dassf(n)≤c·g(n)}
f(n) f ∈ O(?) Example 3n+ 4
O(n) c= 4, n0 = 4
2n
O(n) c= 2, n0 = 0
n2+ 100n
O(n2) c= 2, n0 = 100
n+√ n
O(n) c= 2, n0 = 1
Asymptotic Upper Bounds – Examples
O(g(n)) ={f:N→R+|es existierenc >0undn0∈N so dass für allen≥n0 gilt, dassf(n)≤c·g(n)}
f(n) f ∈ O(?) Example 3n+ 4 O(n) c= 4, n0 = 4 2n
O(n) c= 2, n0 = 0
n2+ 100n
O(n2) c= 2, n0 = 100
n+√ n
O(n) c= 2, n0 = 1
Asymptotic Upper Bounds – Examples
O(g(n)) ={f:N→R+|es existierenc >0undn0∈N so dass für allen≥n0 gilt, dassf(n)≤c·g(n)}
f(n) f ∈ O(?) Example 3n+ 4 O(n) c= 4, n0 = 4 2n O(n) c= 2, n0 = 0 n2+ 100n
O(n2) c= 2, n0 = 100
n+√ n
O(n) c= 2, n0 = 1
Asymptotic Upper Bounds – Examples
O(g(n)) ={f:N→R+|es existierenc >0undn0∈N so dass für allen≥n0 gilt, dassf(n)≤c·g(n)}
f(n) f ∈ O(?) Example 3n+ 4 O(n) c= 4, n0 = 4 2n O(n) c= 2, n0 = 0 n2+ 100n O(n2) c= 2, n0 = 100 n+√
n
O(n) c= 2, n0 = 1
Asymptotic Upper Bounds – Examples
O(g(n)) ={f:N→R+|es existierenc >0undn0∈N so dass für allen≥n0 gilt, dassf(n)≤c·g(n)}
f(n) f ∈ O(?) Example 3n+ 4 O(n) c= 4, n0 = 4 2n O(n) c= 2, n0 = 0 n2+ 100n O(n2) c= 2, n0 = 100 n+√
n O(n) c= 2, n0 = 1
Time Complexity of Algorithms
Time Complexity Analysis
Small n
1 2 3 4 5 6
0 20 40 60
logn n n2
n4 2n
Larger n
2 4 6 8 10 12 14 16 18 20 22 24
0 200 000 400 000 600 000 800 000
logn nn2 n4 2n
“Large” n
10 20 30 40 50 60 70 80 90 100
0 2·1019 4·1019 6·1019 8·1019 1·1020
logn nn2 n4 2n
Faster Primality Testing
First Attempt
Faster Primality Testing
Goal
Time complexity better thanΩ(2n)
Observation
Ifx is not divisible by2, then it also is not divisible by4,6,8, etc. We then only have to check odd numbers
Algorithm only has to test half the numbers Loop is only iterated aroundx/2times
Faster Primality Testing
Goal
Time complexity better thanΩ(2n) Observation
Ifx is not divisible by2, then it also is not divisible by4,6,8, etc.
We then only have to check odd numbers Algorithm only has to test half the numbers Loop is only iterated aroundx/2times
Faster Primality Testing
Goal
Time complexity better thanΩ(2n) Observation
Ifx is not divisible by2, then it also is not divisible by4,6,8, etc.
We then only have to check odd numbers Algorithm only has to test half the numbers Loop is only iterated aroundx/2times
Faster Primality Testing
def primetest2(x):
if x < 2 or (x > 2 and x % 2 == 0):
return False d = 3d = 3 while d < x:
if x % d == 0:
return False d += 2d += 2 return True
Faster Primality Testing
What is the gain?
Loop is iterated roughlyx/2times instead ofxtimes Time complexity improves by a factor of2
Again assumex is encoded usingnbits
Around5·2n/2 = 2.5·2nfundamental operations in total Time complexity is still inO(2n)
ï No asymptotic improvement
Faster Primality Testing
What is the gain?
Loop is iterated roughlyx/2times instead ofxtimes Time complexity improves by a factor of2
Again assumex is encoded usingnbits
Around5·2n/2 = 2.5·2nfundamental operations in total Time complexity is still inO(2n)
ï No asymptotic improvement
Faster Primality Testing
What is the gain?
Loop is iterated roughlyx/2times instead ofxtimes Time complexity improves by a factor of2
Again assumexis encoded usingnbits
Around5·2n/2 = 2.5·2nfundamental operations in total
Time complexity is still inO(2n) ï No asymptotic improvement
Faster Primality Testing
What is the gain?
Loop is iterated roughlyx/2times instead ofxtimes Time complexity improves by a factor of2
Again assumexis encoded usingnbits
Around5·2n/2 = 2.5·2nfundamental operations in total Time complexity is still inO(2n)
ï No asymptotic improvement
Faster Primality Testing
What is the gain?
Loop is iterated roughlyx/2times instead ofxtimes Time complexity improves by a factor of2
Again assumexis encoded usingnbits
Around5·2n/2 = 2.5·2nfundamental operations in total Time complexity is still inO(2n)
ï No asymptotic improvement
Faster Primality Testing
Second Attempt
Faster Primality Testing
Observation
Ifxwithx>2is not a prime number, thenxis divisible by a numberawith 1< a <x
Thenxis also divisible by a numberbwith
a·b=x and 1< b <x
It cannot be the case that
a >√
x and b >√ x, since then
a·b >x
Faster Primality Testing
Observation
Ifxwithx>2is not a prime number, thenxis divisible by a numberawith 1< a <x
Thenxis also divisible by a numberbwith
a·b=x and 1< b <x
It cannot be the case that
a >√
x and b >√ x, since then
a·b >x
Faster Primality Testing
Observation
Ifxwithx>2is not a prime number, thenxis divisible by a numberawith 1< a <x
Thenxis also divisible by a numberbwith
a·b=x and 1< b <x
It cannot be the case that
a >√
x and b >√ x, since then
a·b >x
Faster Primality Testing
Including Modules
Including Modules
So far all functions have been defined in a single file
Modules
Distribute functions over multiple files Files cannot “see” each other
Functions can beimported Structured code
Including Modules
So far all functions have been defined in a single file Modules
Distribute functions over multiple files Files cannot “see” each other
Functions can beimported Structured code
Including Modules
Filefunctions.py
def square_root(n):
i = 1
while i * i < n: # Computer root of next larger square number i += 1
return i
Fileapplications.py
print(square_root(81))
Including Modules
Filefunctions.py
def square_root(n):
i = 1
while i * i < n: # Computer root of next larger square number i += 1
return i
Fileapplications.py
print(square_root(81))
Including Modules
Filefunctions.py
def square_root(n):
i = 1
while i * i < n: # Computer root of next larger square number i += 1
return i
Fileapplications.py
from functions import square_root print(square_root(81))
Including Modules
Filefunctions.py
def square_root(n):
i = 1
while i * i < n: # Computer root of next larger square number i += 1
return i
Fileapplications.py
from functions import * print(square_root(81))
Including Modules
A large number of modules already exists
For instance, there is a modulemathwhich includes a functionsqrt()to compute square roots
print(sqrt(9))
NameError: name ’sqrt’ is not defined
Including Modules
A large number of modules already exists
For instance, there is a modulemathwhich includes a functionsqrt()to compute square roots
print(sqrt(9))
NameError: name ’sqrt’ is not defined
Including Modules
A large number of modules already exists
For instance, there is a modulemathwhich includes a functionsqrt()to compute square roots
print(sqrt(9))
NameError: name ’sqrt’ is not defined
Including Modules
A large number of modules already exists
For instance, there is a modulemathwhich includes a functionsqrt()to compute square roots
from math import sqrt print(sqrt(9))
Output: 3
Faster Primality Testing
def primetest3(x):
if x < 2 or (x > 2 and x % 2 == 0):
return False d = 3
while d < x:
if x % d == 0:
return False d += 2
return True
Faster Primality Testing
from math import sqrt
def primetest3(x):
if x < 2 or (x > 2 and x % 2 == 0):
return False d = 3
wurzelx = sqrt(x) while d <= wurzelx:
if x % d == 0:
return False d += 2
return True
Faster Primality Testing
What is the gain this time?
What is the time complexity of this algorithm? Loop is iterated√
x/2times Time complexity “grows” with√
x Time complexity is inO(√
2n) =O(2n/2) =O(1.415n)
Faster Primality Testing
What is the gain this time?
What is the time complexity of this algorithm?
Loop is iterated√
x/2times Time complexity “grows” with√
x Time complexity is inO(√
2n) =O(2n/2) =O(1.415n)
Faster Primality Testing
What is the gain this time?
What is the time complexity of this algorithm?
Loop is iterated√
x/2times
Time complexity “grows” with√ x Time complexity is inO(√
2n) =O(2n/2) =O(1.415n)
Faster Primality Testing
What is the gain this time?
What is the time complexity of this algorithm?
Loop is iterated√
x/2times Time complexity “grows” with√
x
Time complexity is inO(√
2n) =O(2n/2) =O(1.415n)
Faster Primality Testing
What is the gain this time?
What is the time complexity of this algorithm?
Loop is iterated√
x/2times Time complexity “grows” with√
x Time complexity is inO(√
2n) =O(2n/2) =O(1.415n)
Faster Primality Testing
5 10 15 20 25 30 35 40 45
0 2 000 000 4 000 000 6 000 000 8 000 000 10 000 000