Vous êtes sur la page 1sur 14

// returns the sum of the digits of num

int sumDigits(int num) {

int sum = 0;
int currentDigit;

// four step algorithm:

// step 1: loop until we have no digits left to process


while(num > 0) {

// step 2: find out the rightmost digit


currentDigit = num % 10;

// step 3: add the rightmost digit to our sum


sum += currentDigit;

// step 4: remove the rightmost digit from num


num /= 10;

return sum;

}
An algorithm is written in simple English and is not a formal document. An algorithm
must:

- be lucid, precise and unambiguous


- give the correct solution in all cases
- eventually end

Also note it is important to use indentation when writing solution algorithm because it
helps to differentiate between the different control structures.

1) Finiteness: - an algorithm terminates after a finite numbers of steps.

2) Definiteness: - each step in algorithm is unambiguous. This means that the action
specified by the step cannot be interpreted (explain the meaning of) in multiple ways &
can be performed without any confusion.

3) Input:- an algorithm accepts zero or more inputs

4) Output:- it produces at least one output.

5) Effectiveness:- it consists of basic instructions that are realizable. This means that the
instructions can be performed by using the given inputs in a finite amount of time.
Computational problem
From Wikipedia, the free encyclopedia

Jump to: navigation, search

In theoretical computer science, a computational problem is a mathematical object


representing a collection of questions that computers might want to solve. For example,
the problem of factoring

"Given a positive integer n, find a nontrivial prime factor of n."

is a computational problem. Computational problems are one of the main objects of study
in theoretical computer science. The field of algorithms studies methods of solving
computational problems efficiently. The complementary field of computational
complexity attempts to explain why certain computational problems are intractable for
computers.

A computational problem can be viewed as an infinite collection of instances together


with a solution for every instance. For example in the factoring problem, the instances are
the integers n, and solutions are prime numbers p that describe nontrivial prime factors of
n.

It is conventional to represent both instances and solutions by binary strings, namely


elements of {0, 1}*. For example, numbers can be represented as binary strings using the
binary encoding. (For readability, we identify numbers with their binary encodings in the
examples below.)
Types of computational problems
A decision problem is a computational problem where the answer for every instance is
either yes or no. An example of a decision problem is primality testing:

"Given a positive integer n, determine if n is prime."

A decision problem is typically represented as the set of all instances for which the
answer is yes. For example, primality testing can be represented as the infinite set

L = {2, 3, 5, 7, 11, ...}

In a search problem, the answers can be arbitrary strings. For example, factoring is a
search problem where the instances are (string representations of) positive integers and
the solutions are (string representations of) collections of primes.

A search problem is represented as a relation over consisting of all the instance-solution


pairs, called a search relation. For example, primality can be represented as the relation

R = {(4, 2), (6, 2), (6, 3), (8, 2), (8, 4), (9, 3), ...}

which consist of all pairs of numbers (n, p), where p is a nontrivial prime factor of n.

A counting problem asks for the number of solutions to a given search problem. For
example, the counting problem associated with primality is

"Given a positive integer n, count the number of nontrivial prime factors of n."

A counting problem can be represented by a function f from {0, 1}* to the nonnegative
integers. For a search relation R, the counting problem associated to R is the function

fR(x) = |{y: (x, y) ∈ R}|.

An optimization problem asks for finding the "best possible" solution among the set of all
possible solutions to a search problem. One example is the maximum independent set
problem:

"Given a graph G, find an independent set of G of maximum size."

Optimization problems can be represented by their search relations.


[edit] Promise problems
In computational complexity theory, it is usually implicitly assumed that any string in {0,
1}* represents an instance of the computational problem in question. However,
sometimes not all strings {0, 1}* represent valid instances, and one specifies a proper
subset of {0, 1}* as the set of "valid instances". Computational problems of this type are
called promise problems.

The following is an example of a (decision) promise problem:

"Given a graph G, determine if G has an independent set of size at most 5, or


every independent set in G has size at least 10."

Here, the valid instances are those graphs whose maximum independent set size is either
at most 5 or at least 10.

Decision promise problems are usually represented as pairs of disjoint subsets (Lyes, Lno)
of {0, 1}*. The valid instances are those in Lyes ∪ Lno. Lyes and Lno represent the instances
whose answer is yes and no, respectively.

Promise problems play an important role in several areas of computational complexity,


including hardness of approximation, property testing, and interactive proof systems.

Program development - Steps

Steps to Program Development are...

• System Analysis
• Specification and Design
• Program
• Debug
• Alpha Test
• Beta Test

• Deliver the Software


Program Development - System Analysis

System Analysis involves creating a formal model of the problem to be


solved. The model is created by:

• talking to the users to assess


their needs
• understanding the
complete problem
to be solved

• making a formal
representation of the
system being designed

At this stage a detailed design is written which defines the following:


• Data Structures: defining the format and type of data the program
will use.
• User Interface: the design of the screen the user will see and use to
enter data or display data.
• Inputs: defining the kind of data to enter into the program.
• Outputs: the possible data displayed from the system.
• Algorithms: the methods of calculating outputs depending on the
inputs.

Program Development - Program


Programmers use the specification to write the code necessary to fulfil all
the requirements of the program. The code is a text based file which when
compiled creates the program.

A good programmer will


consider:

• Future Maintenance: any code that may be modified in future and


should be allowed for when writing the code.
• Code Readability: this enables programmers to identify areas of
code quickly and easily.
• Documentation: a document showing how the program works.

Program Development - Debug

Virtually all programs have defects in them called 'bugs' and these need to
be eliminated. Bugs can arise from errors in the logic of the program
specification or errors in the programming code created by a programmer.

Special programming tools assist the programmer in finding and correcting


bugs.

Some bugs are difficult to locate and fixing them is like solving a complex
puzzle.

Program Development - Alpha Test


This is a small scale trial of the program. The application is given to a few
expert users to assess whether it is going to meet their needs and that the
user interface is suitable.

Bugs and missing features due to the application being unfinished will be
found. Any errors in the code and specification will be corrected at this
stage.

Program Development - Beta Test

This is a more wide-ranging trial where the application is given to a


selection of users with different levels of experience.

This is where we hope that the remaining bugs are found, but some may
remain undetected or unfixed.
Program Development - Software Delivery

The completed software is packaged with full documentation and


delivered to the end users.

When they use the software, bugs that were not found during testing
may appear. As these new bugs are reported an updated version of the
software with the reported bugs corrected is shipped as a replacement.

Program development steps


To begin with, writing a program involves several steps (we will consider others in the
future):

1. Define the external specification including the user interface and event handlers
2. Build the user interface
3. Code event handlers and write common code
4. Debug the program
5. Document the program

We will discuss some of these now, and return to others later.


1. The first, most important and creative step is defining the external specification of the
program. You cannot write the instructions for doing something until you know what it is
you want done, so before you start writing a program, you need a clear picture of what it
will do when it is finished. You have to imagine it running -- what does the screen look
like? What actions can the user take? What happens when he or she takes each of those
actions?

This step is analogous to an architect imagining then drawing pictures and plans for a
house to be built. When the architect finishes, he or she turns the plans over to a building
contractor who constructs the house. If the plans were complete and well written, the
house will come out as the architect imagined it.

Similarly the external description of a program should give enough detail that a
programmer could use it to write the program as you envisioned it.

You should prepare a written description, an external specification, of the program you
are going to write before you begin writing it. For a short program, this description may
be only one page long, but for a large program like Microsoft Word, it would be very
long and detailed.

The external specification should show the appearance of the user interface -- which
controls are on the screen and how they are laid out.

It should also specify the events that can occur -- the actions the user can take, and what
the computer should be programmed to do for each of them. (As we will see later, all
events are not caused by user action).

2. Build the user interface using the VS development system.

3. Code the event handlers. For each event you define in step 1, you must write an event
handler, a subprogram telling the computer what to do when that event occurs.

4. When you first run your program, it will not work properly. Debugging is the process
of finding and correcting your errors. In testing a program, you should give it extreme
inputs in an attempt to force errors.

Some IT managers require programmers to write their debugging test plans before
beginning to program. They assume that if the programmer does not have a clear enough
external description to do so, they do not understand the problem well enough to program
it.

5. The job is not finished when the program is working correctly. The programmer must
prepare documents describing both the external specification and the internal design of
the program. This documentation will be of value to users and programmers who must
maintain and modify your program.
Many people may work as a team if a project is large. There might be architects,
programmers, testers and documentation writers.

It may sound like you just work your way through these steps in order, but, in practice,
you will find yourself going back at times. For example, while writing event handlers,
you might decide you need to change the user interface, so you need to back up and
change the external specification.

You might be tempted to skip some of these steps when working on simple programs like
those in this class, but when working on a larger program, that would be a big mistake.
The best way to save time on a programming project is to spend a lot of time on the
external design. A well-designed program will be easy to code, debug and document. As
they say "the best way to go fast is to go slow."
Algorithm LargestNumber
Input: A non-empty list of numbers L.
Output: The largest number in the list L.

largest ← L0
for each item in the list L≥1, do
if the item > largest, then
largest ← the item
return largest

Algorithm for finding factorial of any number.........steps are

1. Take a number as a input from the user.


2. initialize a variable fact=1

3. fact=fact*number
4. number=number-1
5. repeat step 3 to 5 if number>0
6. print the value of fact variable

c++:
int x;
cout<<"enter number :";
cin>>x;
int factorial=1;
for (int i=x; i > 0;i--)
factorial =factorial * i;
cout<<" facotorial of "<<x <<" is "<<factorial<<"\n";
return 0;

Algorithm to find the sum of first n natural numbers:


1. Read n.
2. Initialize N=1.
3. Initialize sum S=0.
4. Calculate S=S+N.
5. Calculate N=N+1.
6. If N>n, then goto step 7 else goto step 4.
7. Write the sum S.
8. Stop.

13.1.2 Strategy 1: Linear Search


Let's try our hand at developing a search algorithm using a simple .be the
computer
. strategy. Suppose that I gave you a page full of numbers in no particular
order and asked whether the number 13 is in the list. How would you solve
this problem? If you are like most people, you would simply scan down the
list
comparing each value to 13. When you see 13 in the list, you quit and tell me
that you found it. If you get to the very end of the list without seeing 13, then
you tell me it's not there.
This strategy is called a linear search. You are searching through the list
of items one by one until the target value is found. This algorithm translates
directly into simple code.
def search(x, nums):
for i in range(len(nums)):
if nums[i] == x: # item found, return the index value
return i
return -1 # loop finished, item was not in list
This algorithm was not hard to develop, and it will work very nicely for
modest-sized lists. For an unordered list, this algorithm is as good as any. The
Python in and index operations both implement linear searching algorithms.
If we have a very large collection of data, we might want to organize it in
some way so that we don't have to look at every single item to determine
where,
or if, a particular value appears in the list. Suppose that the list is stored in
sorted
order (lowest to highest). As soon as we encounter a value that is greater
than
428 Chapter 13. Algorithm Design and Recursion
the target value, we can quit the linear search without looking at the rest of
the
list. On average, that saves us about half of the work. But, if the list is sorted,
we can do even better than this.

def fact(n):
if n == 0:
return 1
else:
return n * fact(n-1)
Do you see how the de_nition that refers to itself turns into a function that
calls
itself? This is called a recursive function. The function _rst checks to see if we
are at the base case n == 0 and, if so, returns 1. If we are not yet at the base
case, the function returns the result of multiplying n by the factorial of n-1.
The
latter is calculated by a recursive call to fact(n-1).
I think you will agree that this is a reasonable translation of the recursive
de_nition. The really cool part is that it actually works! We can use this
recursive
function to compute factorial values.
>>> from recfact import fact
>>> fact(4)
24
>>> fact(10)
3628800
Some beginning programmers are surprised by this result, but it follows
naturally
from the semantics for functions that we discussed way back in Chapter 6.
Remember that each call to a function starts that function anew. That means
it
has its own copy of any local values, including the values of the parameters.
Figure 13.1 shows the sequence of recursive calls that computes 5!. Note
especially
how each return value is multiplied by a value of n appropriate for each
function invocation. The values of n are stored on the way down the chain
and
then used on the way back up as the function calls return.
There are many problems for which recursion can yield an elegant and ef-
_cient solution. The next few sections present examples of recursive problem
solving.\

Algorithm to find the sum of first n natural numbers:


1. Read n.
2. Initialize N=1.
3. Initialize sum S=0.
4. Calculate S=S+N.
5. Calculate N=N+1.
6. If N>n, then goto step 7 else goto step 4.
7. Write the sum S.
8. Stop.

• 5 months ago
100% 1 Vote

Vous aimerez peut-être aussi