Upload
hacong
View
213
Download
1
Embed Size (px)
Citation preview
� Exchanging the values of two variables
� Counting
� Summation of a set of numbers
� Factorial Computation
� Sine Function Computation
� Generation of the Fibonacci Sequence
� Reversing the digits of an integer
� Base Conversion
� Character to number conversion
Fundamental Algorithms 2
� Problem
� Given two variables, a and b, exchange the
values assigned to them.
Fundamental Algorithms 3
� Algorithm Development
� The problem of interchanging the values
associated with two variables involves a very
fundamental mechanism that occurs in many
sorting and data manipulation algorithms.
� To define the problem more clearly we will
examine a specific example:
� Consider that the variables a and b are assigned
values as outlined below:
Fundamental Algorithms 4
� This means that memory cell (or variable) a
contains the value 721, and memory cell (or
variable) b contains the value 463.
� Our task is to replace the contents of a with
463, and the contents of b with 721.
� In other words we want to end up with the
configuration below:
Fundamental Algorithms 5
� To change the value of a variable we can use
the assignment operator as follows:
� Where “ := “ is the assignment operator.
Fundamental Algorithms 6
� Statement (1) “:=“ causes the value stored in
variable b to be copied into variable a.
Fundamental Algorithms 7
� Problem
� Given a set on n student’s examination marks (in
the range 0 to 100) make a count of the number
of students that passed the examination.
� A pass is awarded for all marks of 50 and above.
Fundamental Algorithms 9
� Algorithm development
� Generally a count must be made of the number
of items in a set which posses some particular
property or which satisfy some particular
condition or conditions.
� The problem stated above is called as the
“examination marks” problem.
� Suppose that we are given the set of marks
55,42,77,63,29,57,89
� To make a count of the passes for this set we
examine the first mark( i.e. 55), see if it is ≥50,
and conclude that one student has passed so far.
Fundamental Algorithms 10
� The second mark (i.e, 42) is then examined and
no adjustment is made to the count.
� When we arrive at the third mark we see it is ≥50
and so we add one to our previous count.
� The process continues in a similar manner until
all marks have been tested.
Fundamental Algorithms 11
� After each mark has been processed the current
count reflects the number of students that have
passed in the mark list so far encountered.
� From our example above we see that everytime
we need to increase the count we build on the
previous value. That is,
� For example : when we arrive at mark 57, we
have
� Current_count therefore becomes 4. This means
that the current_count must previous_count + 1.
Fundamental Algorithms 13
� This can be represented by a two step process:
� The essential steps in our pass-counting algorithm can therefore be summarized as:
while less then n marks have been examined do � read next mark, � if current mark satisfies pass requirement then add one
to count.
� Before any marks have been examined the count must have the value zero.
� To complete the algorithm the input of the marks and the output of the number of passes must be included.
Fundamental Algorithms 14
ALGORITHM passcount()
//PROBLEM STATEMENT: Algorithm to count the number of pass marks from a given set of marks.
// INPUT: n marks of type integer >0
//OUTPUT: passcount >=0
passmark�50;
write(“Enter how many marks you want to enter”);
read(n);
write(“Enter n marks each on a separate line”);
i�0;
passcount�0;
while(i<n) do
{
read(m);
if(m>=passmark) then passcount�passcount+1;
i�i+1;
}
write(“Total Pass:”,pass);
return
Fundamental Algorithms 16
� Problem
� Given a set of n numbers design an algorithm
that adds these numbers and returns the
resultant sum.
� Assume n is greater that or equal to zero.
Fundamental Algorithms 18
� One of the most fundamental things that we
are likely to do with a computer is to add a
set of n numbers.
� When confronted with this problem in the
absence of a computer we simply write the
numbers down one under the other and start
adding up the right-hand column.
� For example , consider the addition of 421,
583, and 714.
Fundamental Algorithms 19
� The computer has a built-in device which accepts
two numbers to be added, performs the addition,
and returns the sum of the two numbers
Fundamental Algorithms 20
� The simplest way that we can instruct the computer’s arithmetic unit to add a set of numbers is to write down an expression that specifies the addition we wish to be performed.
� For our three numbers mentioned previously we could write
� The assignment operator causes the value resulting form the evaluation of right-hand side expression (1) to be placed in the memory cell of allocated variable s.
Fundamental Algorithms 21
� The expression (1) will only evaluate 421, 583, and 714, but if we wanted to evaluate other numbers.
� For this task we would need a new program statement that would replace all the constant values in expression (1) by variables as shown below:
� Expression (2) adds any three numbers provided they have been previously assigned as values or contents of a, b, and c respectively.
Fundamental Algorithms 22
� Still there is a serious deficiency – it can add only
a set of three numbers.
� A fundamental goal in designing algorithms and
implementing programs is to make the programs
general enough so that they will successfully
handle a wide variety of input conditions.
� That is, we want a program that will add any n
numbers where n can take on a wide range of
values.
� Conventionally we would write the general
equation as
Fundamental Algorithms 23
� One way to do this is to take the fact that the
computer adds two numbers at a time , and start
adding the first two numbers a1 and a2. That is
� Then proceed by adding a3 to s computed in step
(1)
Fundamental Algorithms 24
� In a similar manner :
� From step 2 we are actually repeating the same
process over and over– the only difference is that
values of a and s change with each step.
� In general for ith step we have:
Fundamental Algorithms 25
� The algorithm we want to develop for
summing n numbers should perform correctly
for all values of n greater than or equal to 0
(i.e., n>=0).
� It must therefore work correctly for the sum
of zero (n=0) and the sum of 1 (n=1)
numbers.
� This means the step(1) we used is not
appropriate.
� However, if we replace i+1 in the general
step(i), by i and substitute i=1 we get:
Fundamental Algorithms 26
� The step (1’) will be correct provided s:=0
before this is executed.
� It follows that all sums for n>=1 can be generated
iteratively.
� For n=0 (which is a special case) we cannot
generate iterations hence the sum is zero itself.
Fundamental Algorithms 27
� Algorithm: sumofnnumbers.txt
� Applications:
� Average calculations
� Variance
� Least squares calculations
Fundamental Algorithms 30
� Problem Statement
� Given a number n, compute n factorial ( written
as n! ) where n ≥ 0.
Fundamental Algorithms 31
� We can start the development of the algorithm
by examining the definition of n!.
� In formulating our design for this problem we
need to keep in mind that the computer’s
arithmetic unit can only multiply two numbers at
a time.
� Applying the factorial definition we get
Fundamental Algorithms 32
� From above we see that 4! contains all the
factors of 3!. We can generalize this by
observing that n! can always be obtained from
(n-1)! by simply multiplying it by n. That is
Fundamental Algorithms 33
� Using this definition we can write the first few
factorials as:
� If we start with p=0!=1 we can rewrite the first
few steps in computing n! as:
Fundamental Algorithms 34
� For (i+1)th step we have.
� This general step can be placed in a loop to
iteratively generate n!.
� The instance where n=0 is a special case which
must be accounted for direct assignment.
Fundamental Algorithms 35
� The central part of the algorithm for computing
n! therefore involves a special initial step
followed by n iterative steps.
� Treat 0! as a special case (p =1).
� Build each of the n remaining products p from its
predecessor by an iterative process.
� Write out the value of n factorial.
Fundamental Algorithms 36
� Algorithm Description
� This algorithm is most usefully implemented as a
function that accepts as input a number n and
returns as output the value of n!.
Fundamental Algorithms 37
� Applications
� Probability
� Statistical
� And mathematical computations.
Fundamental Algorithms 38
� Problem
� Design an algorithm to evaluate the function
sin(x) as defined by the infinite series expansion.
Fundamental Algorithms 39
� Algorithm development
� Studying the expression for sin(x) we see that
powers and factorials following the sequence
1, 3, 5, 7, …
� are required.
� We can easily generate this odd sequence by
starting with 1 and successively adding 2.
� Our problem to compute the general term xi/i!
which can be expressed as
Fundamental Algorithms 40
� The function we need to compute this will
involve the following steps:
� The above algorithm works fine and computes
each term (i.e xi/i!) from the smallest j value
and working upwards.
� But the above algorithm is not that efficient
enough to be the optimal to get the solution.
Fundamental Algorithms 41
� In order to get a efficient solution for the above
problem we can explore this possibility for some
specific terms of the series. For ex
Fundamental Algorithms 42
� From the above example we can then generalize
to get the following term:
� Therefore to generate consecutive terms of the
sine series we can use
Fundamental Algorithms 43
� To get the term to alternate signs we can use the
following execution:
� This will generate alternate positive and negative
terms.
� Finally the initial conditions are as follows:
Fundamental Algorithms 44
� The ith term and summation can be generated
iteratively from the predecessors are:
� We now have an effective iterative mechanism
for generating successive terms of the sine
function.
� The only consideration is how to terminate the
algorithm.
� An important consideration here is the desired
accuracy we required for sin(x).
Fundamental Algorithms 45
� Because x is in the range -1 � � � 1 we can see
that the contribution from higher terms quickly
become very small. For example : 4th term (i.e
x7/7! ) makes upto 0.0002.
� In circumstances like this a useful way to bring
about the termination level is to fix an
acceptable error level (eg: 1 x 10-6) and
generate successive terms until the contributions
of the current term is less than the accepatable
error.
Fundamental Algorithms 46
� Problem
� Generate and print the first n terms of the
Fibonacci sequences where n ≥ 1.
� The first few terms are:
0, 1, 1, 2, 3, 5, 8, 13, …
� Each term beyond the first two is derived from
the sum of its two nearest predecessors.
Fundamental Algorithms 49
� Algorithm development
� From the definition we are given that:
new term = preceding term + term before preceding
term
� The last sentence of the problem statement
suggests we may be able to use the definition to
generate consecutive terms (apart from the first
two ) iteratively.
� Let us define:
Fundamental Algorithms 50
� Then to start with we have :
� When the new term c has been generated we
have the third Fibonacci number.
� To generate the fourth, or next Fibonacci number
, we need to apply the same definition again.
� That is the fourth term is deried from the sum
of the second Fibonacci number and the third
Fibonacci number.
Fundamental Algorithms 51
� Therefore before making the next computation
we must ensure that:
� New term assumes the role of the preceding term
� And what is currently the preceding term must assume
the role of the term before the preceding term.
� That is
Fundamental Algorithms 52
� We can improve the previous algorithm.
� As each new term c is computed, the term
before the preceding term , a , loses its
relevance to the calculation of the next
Fibonacci number.
� To restore its relevance we made the assignment
� We know that all times only two numbers are
necessary to generate the next Fibonacci
number.
� In our previous computation we introduced the
third variable c.
Fundamental Algorithms 54
� As whenever a new Fibonacci is number is
generated the a becomes unusable. We can
therefore keep the a always relevant.
� To keep b relevant repeat the same step 3 again.
Fundamental Algorithms 55
� Working through several more steps confirms that
we can safely iterate on steps 3 and 4 to
generate the required sequence.
� The complete algorithm description can now be
given as follows:
� Algorithm Description
Fundamental Algorithms 56
� Algorithm:
� Fibonacciseries1.txt
� Applications
� The Fibonacci sequence has practical
applications in botany, electrical network theory,
sorting and searching.
Fundamental Algorithms 58
� Problem
� Design an algorithm that accepts a positive
integer and reverses the order of its digits.
Fundamental Algorithms 59
� Algorithm Development
� Digit reversal is a technique that is sometimes
used in computing to remove bias from a set of
numbers.
� It is important in some fast information retrieval
algorithms.
� The following example clearly defines the
relationship of the input to desired output.
INPUT : 27953
OUTPUT: 35972
Fundamental Algorithms 60
� The number 27953 is actually
� To access the individual digits t is probably going to be easiest to start at one end of the number and work through to the other end.
� But the question is from which end?
� As we don’t know how many digits are going to be there we will start with the least significant bit(i.e is the right most digit).
� To do this we need to chop of the least significant digit in the number.
� In other words we end up with 2795 with 3 removed.
Fundamental Algorithms 61
� We can get this by integer division of the original
number by 10.
� This chops of 3 but does not allows us to save it.
� However 3 is the remainder that is got from
dividing 27953 by 10.
� To get this remainder we can use the mod
function. That is
� Therefore if we apply the following two steps.
Fundamental Algorithms 62
� We get the digit 3, and a new number 2795.
� Applying the same two steps the new value of n
we can obtain the 5 digit.
� Now we have a mechanism for iteratively
accessing the individual digits of the input
number.
� Our major concern is to carry out digit reversal.
� When we apply our digit extraction procedure to
the first two digits we acquire first the 3 and
next 5.
� In final output they appear as
3 followed by 5 (or 35)
Fundamental Algorithms 63
� If the original number is 53 we could then we
could obtain its reverse by first extracting 3 ,
multiplying it by 10, and then adding 5 to give
35. That is
� Therefore when we have 35 and then extract 9
we can obtain the sequence 359 by multiplying
35 by 10 and adding 9. that is
Fundamental Algorithms 64
� On closely examining the digit extraction and
reversal process, involves a set of steps that can
be performed iteratively.
� The logic for reversing an integer can be
demonstrated by using a variable dreverse and
use it to get the reverse of an integer as follows:
� Therefore to build the reversed integer we can
use the construct:
Fundamental Algorithms 65
� The value of dreverse initially must be set to 0.
� The termination of the algorithm must be when
all the digits have been extracted.
� With each iteration the number of digits in the
number being reversed is reduced by one,
yeilding the sequence shown in table
Fundamental Algorithms 66
� Algorithm
� reverseOfNumber.txt
� Applications
� Hashing and Information Retrieval
� Database Applications
Fundamental Algorithms 69
� Problem
� Convert a decimal integer to its corresponding
octal representation.
Fundamental Algorithms 70
� Algorithm Development
� Frequently in computing it is necessary to
convert a decimal number to the binary, octal or
hexadecimal number systems.
� To design an algorithm for such conversions we
need to understand clearly what the base change
entails.
� A decimal system uses the ten digits 0,1,2,3,…,9
to represent numbers. For example the decimal
(i.e base 10 ) number 275 by its representation,
is seen to consist of:
Fundamental Algorithms 71
� The actual position of each digit in a number
determines its value.
� Similar conventions apply for the octal (or base 8 ) number system.
� The octal system uses only the eight digits 0,1,2,3,….,7 to represent numbers.
� In octal system the position of each digit determines its value in a similar (but different) way to the decimal system.
Fundamental Algorithms 72
� For example the octal representations of the
decimal number 275 is 423. The octal number
consists of :
� With this groundwork lets start developing the
algorithm.
� Consider that we wish to convert the decimal
number 93 to its octal representation.
Fundamental Algorithms 73
� We know that 93 is made up of 3 x 1 and 9 x 10.
This can be shown diagrammatically as
� The corresponding octal number will be divided
up in blocks of units(1), eights (8), sixty-fours
(64) and so on.
Fundamental Algorithms 74
� Diagrammatically we can show the octal
representation as
� From the diagram we can see that decimal
number 93 is divided into
1 x 64
3 x 8
5 x 1
Fundamental Algorithms 75
� Applying the positional conventions we conclude that the octal representation of 93 decimal is 135.
� The octal number 135 consists of
� To do this programmatically we must do integer division of decimal number by 8.
� Taking the above example by doing integer division of 93 by 8 , we will get how many 8s are in 93
Fundamental Algorithms 76
� We can now explicitly identify the base conversion mechanism.
� In changing a decimal number to its octal
representation we start dividing the decimal number by 8.
� The remainder of this operation is the lease significant digit (i.e 5) of the octal representation.
� The quotient (i.e 11) is then taken and divided by 8.
� The remainder of this operation is the second least significant digit of octal representation.
Fundamental Algorithms 77
� The process of dividing the quotient and using the
remainder as the next least significant digit of the
octal representation continues until a zero quotient is
encountered.
� This algorithm involves iterative process where
successive octal digits are derived as remainders
from a sequence of quotients, each of which is in
turn derived from its predecessors by division by
8.
� For the above example we have
Fundamental Algorithms 78
� For ith step:
� The essential steps in the algorithm are:
� Initilize the quotient q to the decimal number to be
converted.
� Derive the octal digits iteratively using succession of
the remainder and quotient computation.
� Terminate the process when the quotient reaches 0.
Fundamental Algorithms 79
� Problem
� Given a character representation of an integer
convert it to conventional representational
decimal format.
Fundamental Algorithms 81
� Algorithm Development � Before we get to the solution to this conversion
problem, we must fully appreciate the difference between the character representation of an integer and its conventional number representation.
� The upper and lower case alphabetic characters, the ten digits and various punctuation and control characters make up only about one hundred different characters.
� In contrast to this, the range of different integers (and real numbers) that are needed may extend into the millions, the billions and even further.
Fundamental Algorithms 82
� Numbers are represented in the computer in
binary positional notation using just 0 and 1
digits.
� For example 221 is written as 11011101 in binary.
� From above example we see that 221 requires
only 3 decimal digits whereas 8 digits are used to
store its binary equivalent.
� It is therefore very wasteful of computer to store
only one character in the basic storage unit of
the computer.
� To make this packing possible it assign fixed 8-bit
codes to the one hundred or so characters.
Fundamental Algorithms 83
� One of the coding systems that uses this
techniques is the American Standard Code for
Information Interchange or ascii code.
� In Ascii 23 does not have a value of 2 tens and 3
units.
� It rather uses decimal values 50 and 51 to
represent 2 and 3.
� Our task is therefore to accept a number as
input and convert it to decimal conversion.
� For example suppose we wanted to convert the
four-character 1984 to the decimal number 1984.
Fundamental Algorithms 84
� The representation can be
� To get the appropriate decimal digit in each case
we have had to subtract 48 (the ascii value of
character 0) from the ascii value of each
character.
� Having progressed this far, our next step is to use
the digits to construct the corresponding decimal
number.
Fundamental Algorithms 85
� That is for our example to convert character
representation 1984 to decimal we can follow
� The shifting to the left mechanism can be
obtained at each step by multiplying the previous
decimal value by 10 and adding in the current
decimal digit.
Fundamental Algorithms 86