Lec11 - iitg.ac.in · Title: Microsoft PowerPoint - Lec11 Author: abs Created Date: 2/9/2017...

27
CS101 Introduction to computing Problem Solving (Computing) A. Sahu and S. V .Rao Dept of Comp. Sc. & Engg. Dept of Comp. Sc. & Engg. Indian Institute of Technology Guwahati 1

Transcript of Lec11 - iitg.ac.in · Title: Microsoft PowerPoint - Lec11 Author: abs Created Date: 2/9/2017...

Page 1: Lec11 - iitg.ac.in · Title: Microsoft PowerPoint - Lec11 Author: abs Created Date: 2/9/2017 10:54:30 PM

CS101 Introduction to computing 

Problem Solving(Computing) 

A. Sahu and S. V .RaoDept of Comp. Sc. & Engg.Dept of Comp. Sc. & Engg.

Indian Institute of Technology Guwahati

1

Page 2: Lec11 - iitg.ac.in · Title: Microsoft PowerPoint - Lec11 Author: abs Created Date: 2/9/2017 10:54:30 PM

Outline• Loop invariant and loop termination• Man Problem Sol ing E amples• Many Problem Solving Examples

–7 Problems (Solution Method not given)

–3 problems (Solution Method given)p (So u o e od g e )

f G “ l iReference : R G Dromey, “How to solve it by Computer”, Pearson Education India, 2009 

2

Page 3: Lec11 - iitg.ac.in · Title: Microsoft PowerPoint - Lec11 Author: abs Created Date: 2/9/2017 10:54:30 PM

Problem Solving Example • Set A  (Solution Method not given)

1 N h f X1. Nth Power of X 2. Square root of a number 3. Factorial of N 4 Reverse a number4. Reverse a number 5. Finding value of unknown by  question 

answersanswers 6. Value of Nth  Fibonacci Number7. GCD to two numbers

3

Page 4: Lec11 - iitg.ac.in · Title: Microsoft PowerPoint - Lec11 Author: abs Created Date: 2/9/2017 10:54:30 PM

Problem Solving Example 

• Set B  (Solution Method given)1. Finding values Sin(x) using series sum 2 Value of PI2. Value of PI 3. Finding root of a function Bisection  

Methods

4

Page 5: Lec11 - iitg.ac.in · Title: Microsoft PowerPoint - Lec11 Author: abs Created Date: 2/9/2017 10:54:30 PM

Problem    1

The nth power of X

Page 6: Lec11 - iitg.ac.in · Title: Microsoft PowerPoint - Lec11 Author: abs Created Date: 2/9/2017 10:54:30 PM

The nth power of X• Problem: Given some  integer x. write a program that computes the nth power x, where  n is positive integer considerably   greater than 1.

• Evaluating expression p=xnProd=1;for (i=1; i<=n; i++){for (i=1; i<=n; i++){

Prod= Prod * x;}

• Naïve or straight‐forward approachHow many multiplication:  ny pRequire n steps 

Assumption : all basic operations on integers take constant time

Page 7: Lec11 - iitg.ac.in · Title: Microsoft PowerPoint - Lec11 Author: abs Created Date: 2/9/2017 10:54:30 PM

The nth power of X• Is there any better approach?• From basic algebra

– if n is even == > Xn = Xn/2.Xn/2

– If n is odd and n=2m+1 ==>  Xn= X2m+1= xm . xm . x • From this above fact, can we calculate Xn in fewer steps A h• Approach– Binary representation of n,     X23 Example 23=(10111)2=1x24+0x23+1x22+1x21+1x20– X23 Example  23=(10111)2=1x24+0x23+1x22+1x21+1x20= 16+0+4+2+1

– Start from right to leftg• 1x24+0x23+1x22+1x21+1x20

Page 8: Lec11 - iitg.ac.in · Title: Microsoft PowerPoint - Lec11 Author: abs Created Date: 2/9/2017 10:54:30 PM

Approach/Algorithm 1. Initialize the power sequence and product variable   (let initial value of n is n0=n)

Product=1; ProdSequence=x;2. Do while n > 0 repeat p2.1  if the next most  binary digit of n is one then  Product = Product * ProdSecuence;2.2  n = n /2;2.3 ProdSecuence *= ProdSecuence;2.3  ProdSecuence  ProdSecuence;

//Invariant Product*ProdSecuencen=x^n0 n>=0//Invariant Product ProdSecuencen=x^n0 , n>=0

Assumption : all basic operations on integers take constant time

Page 9: Lec11 - iitg.ac.in · Title: Microsoft PowerPoint - Lec11 Author: abs Created Date: 2/9/2017 10:54:30 PM

Approach• Binary representation of n,     • X23 Example  p23=(10111)2=1x24+0x23+1x22+1x21+1x20 = 16+0+4+2+1

• Start from right to left1x24+0x23+1x22+1x21+1x20

• Approach– Successive generation of x x2 x4 x8 x16Successive generation of x, x , x , x , x , …– Inclusion of the current power member into accumulated product when the correspondingaccumulated product when the corresponding binary digit is 1

Page 10: Lec11 - iitg.ac.in · Title: Microsoft PowerPoint - Lec11 Author: abs Created Date: 2/9/2017 10:54:30 PM

ApproachBefore Loop

Odd b Ri ht M t Bit

1 0 1 1 1p

Odd number or  Right Most Bit

P=X7.X16=X23

P=X7 P=X3.X4

=X7

P=X.X2=X3

P=P.PS=X

P=1

=X7

X32 X16 X8 X4 X2 PS=XX32 X16 X8 X4 X2 PS=X

N=0 N=1 N=2 N=5 N=11 N=23X23.(X32)0

=X23X7.(X16)1

=X23X7.(X8)2

=X23X3.(X4)5=X23

X.(X2)11

=X23P*PSn=1 X23X X X =1.X

Loop Invariant

Page 11: Lec11 - iitg.ac.in · Title: Microsoft PowerPoint - Lec11 Author: abs Created Date: 2/9/2017 10:54:30 PM

C –Code for Xn

int n, x, Prod, ProdSeq;// Put code for Input n x// Put code for Input n, xProd=1; ProdSeq=x;while(n > 0) {( ) {if ((n%2)==1){

Prod=Prod*ProdSeq;}

n=n/2;ProdSeq = ProdSeq* ProdSeq;ProdSeq = ProdSeq* ProdSeq;

}//Put code to Display Prod as Xn//Put code to Display Prod as X

11Assumption : all basic operations on integers take constant time

Page 12: Lec11 - iitg.ac.in · Title: Microsoft PowerPoint - Lec11 Author: abs Created Date: 2/9/2017 10:54:30 PM

Problem    2

The square root problem :  sqrt(X)

Page 13: Lec11 - iitg.ac.in · Title: Microsoft PowerPoint - Lec11 Author: abs Created Date: 2/9/2017 10:54:30 PM

The square root problem• Problem: Write a program that computes the square root of a given number.

• Is the problem definition clear?– If 25 is the input, then 5 is the output– If 81 is the input, then 9 is the output– If 42 is the input, then ?

• For non perfect squares the square root is a• For non perfect squares, the square root is a real number

• So the output should be close to the real• So the output should be close to the real square root

• How close? to a given accuracy• How close? to a given accuracy 

Page 14: Lec11 - iitg.ac.in · Title: Microsoft PowerPoint - Lec11 Author: abs Created Date: 2/9/2017 10:54:30 PM

A more precise specificationp p• Problem: Write a program that given a 

b l l hnumber m outputs a real value r such that – r*r differs from m by a given accuracy value eaccuracy value e

• More precisely, the program outputs rh hsuch that 

|r*r ‐m| < e| |

Page 15: Lec11 - iitg.ac.in · Title: Microsoft PowerPoint - Lec11 Author: abs Created Date: 2/9/2017 10:54:30 PM

Solution StrategyGuess and Correct Strategy:1 Choose an initial guess r less thanm1. Choose an initial guess r less than m2. If r*r > m then keep decreasing r by 1 until r*r

is less than or equal tomis less than or equal to m.3. If r*r < m then keep increasing r by 0.1, … until 

r*r exceeds or equalsmr r exceeds or equals m4. If r*r > m then decrease r by 0.01 until r*r

exceeds or equalsmexceeds or equals m.

...• Terminate the computation when  r*r equals m

or differs fromm by a given small number. 

Page 16: Lec11 - iitg.ac.in · Title: Microsoft PowerPoint - Lec11 Author: abs Created Date: 2/9/2017 10:54:30 PM

Idea

Desired square root fr

om 

olution 

eviatio

nesire

d so

De

De

• Number of iteration depends upon the initial guess

Number of Iterations

Number of iteration depends upon the initial guess• If m is 10,00,000 and the initial guess is 300 then over 700 steps are needed

• Can we have a better strategy?

Page 17: Lec11 - iitg.ac.in · Title: Microsoft PowerPoint - Lec11 Author: abs Created Date: 2/9/2017 10:54:30 PM

Towards a better strategy• The basic idea of the strategy is to obtain a series of guesses thatg– falls on either side of the actual value– narrows down closer and closernarrows down closer and closer

• To make the guess fall on either sideincrease/decrease the guess systematically– increase/decrease the guess systematically

• To narrow the guessh f /d d d– the amount of increase/decrease is reduced

• Improving the strategy– faster ways of obtaining new guess from the old one

Page 18: Lec11 - iitg.ac.in · Title: Microsoft PowerPoint - Lec11 Author: abs Created Date: 2/9/2017 10:54:30 PM

One Strategygy• Given a guess a for square root of m

–m/a falls on the opposite side/ pp

– (a + m/a)/2, can be the next guess– Why this guess? Make next guess closer to sqrt(m)Why this guess?  Make next guess closer to sqrt(m) based on current guess.  

• This gives rise to the following solution– start with an arbitrary guess, r_0– generate new guesses r_1, r_2, etc by using the averaging formulaaveraging formula.

• When to terminate?when the successive guesses differ by a given small– when the successive guesses differ by a given small number

Page 19: Lec11 - iitg.ac.in · Title: Microsoft PowerPoint - Lec11 Author: abs Created Date: 2/9/2017 10:54:30 PM

The  ApproachflInput  float m, e,  assume: m>0, 0<  e > 1

Output float r1, r2

Loop Invariant : |( * ) | |( * )| | ||(r2*r2‐m) | <= |(r1*r1‐m)|, |r1‐ r2|< e  

/1. r1 = m/2,  r2 = r12.  Do while (|r1 ‐ r2| > e) steps 2.1 and 2.2

2 12.1   r1 = r22.2   r2 = (r1+m/r1)/2

Page 20: Lec11 - iitg.ac.in · Title: Microsoft PowerPoint - Lec11 Author: abs Created Date: 2/9/2017 10:54:30 PM

C  Code :  Square root of m 

fl t 1 2float m, e, r1, r2;// Put code for Input m, er1=m/2;r1=m/2; r2=r1;while(abs(r1-r2) > e) {( ( ) ) {

r1=r2;r2=(r1+m/r1)/2;

}//Put code to Display root as r2

20

Page 21: Lec11 - iitg.ac.in · Title: Microsoft PowerPoint - Lec11 Author: abs Created Date: 2/9/2017 10:54:30 PM

Analysis of the Approach

• Is it correct? Find the loop invariant pand bound function

• Can the algorithm be improved?Can the algorithm be improved?• More general techniques available

Numerical analysis– Numerical analysis

Page 22: Lec11 - iitg.ac.in · Title: Microsoft PowerPoint - Lec11 Author: abs Created Date: 2/9/2017 10:54:30 PM

Problem    3

Factorial Computation

Page 23: Lec11 - iitg.ac.in · Title: Microsoft PowerPoint - Lec11 Author: abs Created Date: 2/9/2017 10:54:30 PM

Factorial Computation• Given a number n, compute the factorial of nof n

• Assume n >= 0• What is factorial?

– 0! = 1 1! = 1 2! = 1*2 = 20! = 1, 1! = 1, 2! = 1 2 = 2– 3! = 1*2*3 = 6

* * * *– 4! = 1*2*3*4* = 24

• n! = 1*2*...*(n‐1)*n, for n>=1( ) ,

Assumption : all basic operations on integers take constant time

Page 24: Lec11 - iitg.ac.in · Title: Microsoft PowerPoint - Lec11 Author: abs Created Date: 2/9/2017 10:54:30 PM

The algorithm/Approach• Observation: For n>=1, n! is (n‐1)! multiplied by n

• Strategy: Given n, compute n! by successively computing 1!, 2!, etc. till n!

Input n, Output FactInput n,  Output Fact1.  initialize fact to  1 and index to 12 do while (index < = n) steps 2 1 and 2 22.  do  while (index  < = n) steps 2.1 and 2.2

2.1 fact = fact * index2.2 index = index + 12.2 index   index   1

Page 25: Lec11 - iitg.ac.in · Title: Microsoft PowerPoint - Lec11 Author: abs Created Date: 2/9/2017 10:54:30 PM

Analysis of Factorial Algorithm  • Is the solution correct?• Loop invariant: At the beginning of each p g giteration,– fact holds the partial product 1 * . . . * (index‐1)fact holds the partial product 1   . . .   (index 1)

• When the loop terminates, index = (n+1)fact then holds (1 * * n)– fact then holds  (1 * ... * n)

• Does the loop terminate?h b d f ( d )– There is a bound function: (n + 1 – index)

– The bound function always >= 0– It decreases in each iteration

Page 26: Lec11 - iitg.ac.in · Title: Microsoft PowerPoint - Lec11 Author: abs Created Date: 2/9/2017 10:54:30 PM

Efficiency AnalysisEfficiency Analysis• Assumption : all basic operations on integers take constant time

• How many operations?– n multiplicationsp

• Can we do better? • Yes, there is a method using (log n) operationsYes, there is a method using (log n) operations

– The Striling’s approximation n!= sqrt(2.π.n). (n/e)nn!   sqrt(2.π.n). (n/e)

– Approximated Value (not exact)– Square root can be done in log time– The nth power of x can be done time log time

Assumption : all basic operations on integers take constant time

Page 27: Lec11 - iitg.ac.in · Title: Microsoft PowerPoint - Lec11 Author: abs Created Date: 2/9/2017 10:54:30 PM

Thanks

27