3.Algorithms I
3.Algorithms I
‣ A notation system
‣ Output: Draw any square of side length |PQ| Find R, S, s.t. PQRS is the square
1. Draw line L1 ⟂ PQ passing P
How long?
Concurrent
b. Draw line L2 ⟂ PQ through Q
4. Draw PQRS
1. PQRS is a square with side |PQ| No matter what P and Q are
☚
a * a * a * .. n times
Python:
Create ‘new version’ Python:
‣ Iterate n times of P (i is hidden) P=1
P=1
for i in range(n):
Pi+1 = Pi * a P=1 i=0
Not P=P*a
n times: while(i < n):
With P0 = 1 mathematical
equality ☚ P=P*a i=i+1
‣ Why is this correct? P=P*a
☚
Indentation based grouping
‣ Can this be done in fewer than n multiplications?
-1
• Let b = a*a
• Let c = b*b?
- b * b * b .. n/2 times What if n is odd?
n/2 multiplications
• We will revisit this
GCD(a,b), given positive integers a, b Iterative Procedure
‣if Euclid’s
(a < b):
algorithm (WLOG, assume b < a) GCD(60, 18)Initialized?
if (a < b):
if (a < b): if (a < b):
•(a,b)
GCD(a, b) = GCD(a-b, b). If a is divisible by b, GCD(a, b) = b 42
= (b,a) (a,b) = (b,a) Test for (a,b) = (b,a) (a,b) = (b,a)
60%18
equality 24 ?
if(b =- 0):
GCD(a-b,Recursion while True:
b) = GCD(a-2b, % b if(a-b <while
rem = a 2b-a)
b) if(a-b > b); Or GCD(a-b, b) rem > 0:
☚
6
☚
return a rem = a % b while rem > 0: rem = a % b
• Keep repeating. But how many times can be subtract?
else: if(rem == 0): return b rem = a % b (a, b) = (b, rem)6)
= GCD(18,
•return
GCD(a, b) = GCD(b,
GCD(b, a%b) a%b), (a, b)Or=b(b,
if a%b
rem) = 0 (a, b) = (b, rem) return b
otherwise Is rem = 0?
☚
if (a < b):
if (a < b) swap values such that a >= b ☚ if (a < b): sav = b
Repeat until rem > 0: b=a b=a
rem = a % b a=b a=b
result b = rem and a = b ☚ b = rem then a = b Python: (a, b) = (b, a)
a=b b = rem
Brief Review
‣ How to think algorithmically
• Know the elementary steps, and how to build on top of them
• Decide the important cases and what to do for each case conditions
• Understand how to break complex operations into simpler ones
‣ How to express algorithms creates function
☚
P=1
• Step-by-step recipe (Imperative style) def Power(a,n):
i=0
• Expressions combining many operations P=1
while i < n:
for i in range(n):
• Case-by-case description of actions i=i+1
P=P*a
‣ Converting algorithms into programs P=P*a
return P
Simple English symbols, no greek/subscripts (word is ok)
function’s output
☚
Subscripts are hidden
Operators
☚
Iterate
☚
Iterate,
☚
Mind the spaces = * / % == () :
keep checking condition that many times