hw2solns - Discrete Mathematics, Spring 2004 Homework 2...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Discrete Mathematics, Spring 2004 Homework 2 Sample Solutions 3.2 #32. Write an algorithm whose input is a sequence s 1 , . . . , s n of numbers and another number x . The algorithm returns true if s i + s j = x for some i negationslash = j , and false otherwise. Solution . Here is a possible implementation: procedure pairsum ( s, n, x ) for i := 1 to n 1 do begin for j := i + 1 to n do begin if s i + s j = x then return( true ) end end return( false ) end pairsum 3.3 #3. Use the Euclidean algorithm (Algorithm 3.3.7) to find the greatest common divisor of 220 and 1400. Solution . The implementation of the Euclidean algorithm in the text is printed below: Procedure gcd ( a, b ) if a < b then swap( a, b ) while b negationslash = 0 do begin r := a mod b a := b b := r end return( a ) end gcd Plugging in a = 1400 and b = 220 into this algorithm, we obtain the following values for a and b after each iteration of the while loop: 1 1. a = 220, b = 1400 mod 220 = 80, 2. a = 80, b = 220 mod 80 = 60, 3. a = 60, b = 80 mod 60 = 20, 4. a = 20, b = 60 mod 20 = 0. Hence the greatest common denominator is 20. 3.4 #16. Write a recursive algorithm whose input is a bit string and whose output is a rearranged bit string in which all of the zeros precede all of the ones. Give a proof using mathematical induction that your algorithm is correct. Solution . Here is a possible implementation (certainly not the most efficient): 1 . procedure rearrange ( s, n ) 2 . if n = 1 then 3 . return 4 . j := n 5 . for i := 1 to n 1 do 6 . begin 7 . if s i = 1 then 8 . j := i 9 . end 10 . swap( s j...
View Full Document

This note was uploaded on 06/12/2011 for the course MATH 103 taught by Professor Wouters during the Spring '08 term at Wisc Oshkosh.

Page1 / 5

hw2solns - Discrete Mathematics, Spring 2004 Homework 2...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online