You are on page 1of 35

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
Outline
• Loop invariant and loop termination
• Many Problem Solving Examples
Man Problem Sol ing E amples
–7 Problems (Solution Method not 
given)
p (So u o e od g e )
–3 problems (Solution Method given)

Reference : R G Dromey, “How to solve it 
f G “ l i
by Computer”, Pearson Education India, 
2009 
2
Problem Solving Example 
• Set A  (Solution Method not given)
1 Nth Power of X 
1. Nh fX
2. Square root of a number 
3. Factorial of N 
4 Reverse a number 
4. Reverse a number
5. Finding value of unknown by  question 
answers 
answers
6. Value of Nth  Fibonacci Number
7. GCD to two numbers
3
Problem Solving Example 
• Set B  (Solution Method given)
1. Finding values Sin(x) using series sum 
2 Value of PI 
2. Value of PI
3. Finding root of a function Bisection  
Methods

4
Problem    1

The nth power of X
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=xn
Prod=1;
for (i=1; i<=n; i++){
Prod= Prod * x;
}
• Naïve or straight‐forward approach
How many multiplication:  n
y p
Require n steps 
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 
• Approach
A h
– Binary representation of n,     
– X23 
23 Example  23=(10111)2=1x2
Example 23=(10111)2=1x24+0x23+1x22+1x21+1x20
= 16+0+4+2+1
– Start from right to left
g
• 1x24+0x23+1x22+1x21+1x20
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 
p
2.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*ProdSecuence =x^n0 n>=0
Approach
• Binary representation of n,     
• X23 Example  
p
23=(10111)2=1x24+0x23+1x22+1x21+1x20 = 
16+0+4+2+1
• Start from right to left
1x24+0x23+1x22+1x21+1x20
• Approach
Successive generation of x x2, xx4, xx8, xx16, …
– Successive generation of x, x
– Inclusion of the current power member into 
accumulated product when the corresponding
accumulated product when the corresponding 
binary digit is 1
Approach
Before Loop
p
Odd
Odd number or  Right Most Bit
b Ri ht M t Bit

1 0 1 1 1
P=X7.X P=X7 P=X3.X P=X.X2 P=P.PS P=1
16=X23 4
=X3 =X
=X7

X32 X16 X8 X4 X2 PS=X


N=0 N=1 N=2 N=5 N=11 N=23
X23.(X32)0 X7.(X16)1 X7.(X8)2 X3.(X4)5 X.(X2)11 P*PSn
=X23 X23
=X X23
=X =X23 X23
=X =1 X23
=1.X
Loop Invariant
C –Code for Xn
int n, x, Prod, ProdSeq;
// Put code for Input nn, x
Prod=1; ProdSeq=x;
while(n
( > 0)) {
if ((n%2)==1){
Prod=Prod*ProdSeq;
}
n=n/2;
ProdSeq = ProdSeq* ProdSeq;
}
//Put code to Display Prod as Xn
11
Problem    2

The square root problem :  sqrt(X)
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
For non perfect squares, the square root is a 
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
A more precise specification
p p
• Problem: Write a program that given a 
number m
b outputs a real value r
l l such 
h
that 
– r*r differs from m by a given 
accuracy value e
accuracy value e
• More precisely, the program outputs r
such that 
h h
||r*r ‐ m| < e
|
Solution Strategy
Guess and Correct Strategy:
1 Choose an initial guess r
1. an initial guess r less than m
less than m
2. If r*r > m then keep decreasing r by 1 until r*r
is less than or equal to m
is less than or equal to m.
3. If r*r < m then keep increasing r by 0.1, … until 
rr*rr exceeds or equals m
exceeds or equals m
4. If r*r > m then decrease r by 0.01 until r*r
exceeds or equals m
exceeds or equals m.
...
• Terminate the computation when  r*r equals m
or differs from m by a given small number. 
Idea

olution 
eviation from  Desired square 
esired so root
De
De

Number of Iterations

• Number
Number of iteration depends upon the initial guess
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?
Towards a better strategy
• The basic idea of the strategy is to obtain a 
g
series of guesses that
– falls on either side of the actual value
– narrows down closer and closer
narrows down closer and closer
• To make the guess fall on either side
– increase/decrease the guess systematically
the guess systematically
• To narrow the guess
– the amount of increase/decrease is reduced
h f /d d d
• Improving the strategy
– faster ways of obtaining new guess from the old 
one
One Strategy
gy
• 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
Why this guess?  Make next guess closer to sqrt(m) 
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 formula
averaging formula.
• When to terminate?
– when
when the successive guesses differ by a given small 
the successive guesses differ by a given small
number
The  Approach
Input  float m, e,  assume: m>0, 0<  e > 1
fl
Output float r1, r2

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

1. r1 = m/2,  r
/ 2 = r1
2.  Do while (|r1 ‐ r2| > e) steps 2.1 and 2.2
2 1 1 = r2
2.1   r
2.2   r2 = (r1+m/r1)/2
C  Code :  Square root of m 

float
fl t m, e, r1,
1 r2;
2
// Put code for Input m, e
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
Analysis of the Approach
• Is it correct? Find the loop
p invariant
and bound function
• Can the algorithm be improved?
• More general techniques available
– Numerical analysis
Problem    3

Factorial Computation
Factorial Computation
• Given a number n, compute the factorial 
of n
of n
• Assume n >= 0
• What is factorial?
– 0! = 1, 1! = 1, 2! = 1
0! = 1 1! = 1 2! = 1*2 2 = 2
=2
– 3! = 1*2*3 = 6
– 4! = 1*2*3*4* = 24
* * * *
• n! = 1*2*...*(n‐1)*n, for n>=1
( ) ,
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
n, Output Fact
1.  initialize fact to  1 and index to 1
2 do while (index < = n) steps 2 1 and 2 2
2.  do  while (index  < = n) steps 2.1 and 2.2
2.1 fact = fact * index
2.2 index = index 
2.2 index  index + 1
1
Analysis of Factorial Algorithm  
• Is the solution correct?
• Loop invariant: At the beginning of each 
p g g
iteration,
– fact holds the partial product 1 
fact holds the partial product 1 * . . . 
. . . * (index
(index‐1)
1)
• When the loop terminates, index = (n+1)
– fact then holds  (1 * ... * n)
fact then holds (1 * * n)
• Does the loop terminate?
– There is a bound function: (n + 1 –
h b df ( index)
d )
– The bound function always >= 0
– It decreases in each iteration
Efficiency Analysis
Efficiency Analysis
• How many operations?
– n multiplications
n multiplications
• Can we do better? 
• Yes, there is a method using (log n) 
Yes there is a method sin (log n)
operations
– The Striling’s
The Striling’s approximation 
approximation
n!=  sqrt(2.π.n). (n/e)n
– Approximated Value (not exact)
i d l ( )
– Square root can be done in log time
Th th power of x can be done time log time
– The n f b d ti l ti
Problem    4

Reversing Digit of a Number
Reversing Digit of a Number
Problem: Reversing the Digits of an integer

Examples:
p
Input:  58902
Output: 20985

Input: 4300
Output: 34
Output: 34
Top Down Strategy
p gy
• The above solution follows the top‐down 
methodology
– Break the problem into two or more sub problems
– Obtain the solutions for the sub problems
p
– Combine the solutions to get the solution for the 
original problem
• Many Large problems can be solved using top‐
down approach
• Obtain the algorithm for the problem using the 
two previous algorithm
Reversing Digit of a Number
Problem: Reversing the Digits of an integer
Examples:
Input:  58902       Output: 20985
( )
R(58902) = 2x10 4+R(5890)  
( )
// you need to know how many digit before hand
2x104+0x10
= 2x10 0x103+R(589)
R(589)
= 2x104+0x103+9x102+R(58)
= 2x104+0x103+9x102+8x101+R(5)
= 2x10 Decreasing
Decreasing 
4 3 2 1 power of 10 
= 2x10 +0x10 +9x10 +8x10 +5 
= 20000+0000+900+80+5
= 20000+0000+900+80+5
Reversing Digit of a Number
Problem: Reversing the Digits of an integer
Examples:
Input:  58902       Output: 20985
( ) (
R(58902) = 2+R(5890)   )
= 2x10+0+R(589)
= (2x10
(2x10+0)x10+9+R(58)
0)x10 9 R(58)
=  ((2x10+0)x10+9)x10+8+R(5)
= (((2x10+0)x10+9)x10+8)x10+5
=  (((2x10+0)x10+9)x10+8)x10+5 Increasing 
Increasing
power of 10 
Approach : Digit Reversal
Input:  N is k digit number to be reversed
Output: 
p RevNum the reversed number
1. q = N
2. RevNum = 0 0
3. Do while (q > 0) steps 3.1,3.2,3.3 
3 1 rem = q mod
3.1 rem = q mod 10
3.2 RevNum = RevNum *10 + rem
33
3.3 q = q / 10
/ 10
Invariant: After jth iteration q={d1}{d2}..{dk‐j} 
and RevNum={d
dR N {dk}{dk‐1}…{d
} {dk‐j‐1}
C  Code  to reverse a number 
int n, RevNum, Rem, q;
// Put code for Input n
q=n;
RevNum=0;
;
while(n != 0) {
Rem = n%10;
RevNum=RevNum*10+ Rem;
n=n/10;
}
//Put code to Display RevNum

33
Analysis of the Approach
y pp
• Is the algorithm correct?
g
• Does it terminate?
– Yes, 
Y
• How many number of iterations?
– Take number of digit time/iteration
• How many number of operations?
How many number of operations?
– Per Iteration: One  mod, 1 mul, 1 add, 1 div 
Thanks

35

You might also like