Docsity

Long Division and Algorithms, Slides of Computer Science

Partial preview of the text

Download Long Division and Algorithms and more Slides Computer Science in PDF only on Docsity!

Algorithms and Software

Chapter 7

Some of Chapter 8

Sections 17.2, 17.

What is an Algorithm?

An algorithm for solving a problem is:

  • an unambiguous set of instructions
  • that can be executed in a finite amount of time and
  • that, when finished, has solved the problem.

Long Division

Long Division

quotient(n, m, desired digits):

place decimal point in correct place in answer

while n != 0 and number of iterations < desired digits:

# find the shortest prefix of n into which m goes.

# divide m into it.

write the result as the next digit of answer

n = remainder concatenated with remaining part of m

return(answer)

n

m

Preconditions

When we specify a problem, we specify conditions that the

programmer may assume hold at the time that the program

begins.

Preconditions for our division program:

quotient(n, m):
while n != 0:
divide m into the shortest prefix of n into which it goes:
for i in range(10):
if (i+1)*m > first chunk:
i is the result break
write the result as the next digit of answer
n = remainder
return(answer)

n

m

Swapping Two Values

35

12

An algorithm to swap the values:

X:

Y:

Swapping Two Values

35

12

An algorithm to swap the values:

X:

Y:

z = x

x = y

y = z

Z:

Divide and Conquer

def chess(board): while game_on: internal_board = scan(board) move = choose(internal_board) play(move, board)

Recall the idea: decompose into

pieces that make sense.

Rolling Dice

What is the frequency of

each total?

Rolling Dice

How can we fill in the table

with the totals?

Rolling Dice

What is the frequency of

each total?

Rolling Dice

freqs = [0] * 13

for i in range(6): for j in range(6): tot = dice[i][j] freqs[tot] += 1

Rolling Dice

Do we believe this answer?

  • Count the totals.

Rolling Dice

Do we believe this answer?

  • Count the totals.
  • Simulate throwing a lot of dice.