Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

4. Use a loop invariant to find any error(s) in the following algorithms. If any errors are found, correct them and redo the loop invariant.

image text in transcribed
4. Use a loop invariant to find any error(s) in the following algorithms. If any errors are found, correct them and redo the loop invariant. You must submit the proof of correctness showing the errors in algorithm logic, as well as for your fixed algorithm. Note: There is no general recipe for finding a loop invariant of an algorithm. It could be helpful to see previous assignments of this course to understand how to find a loop invariant and use it to show your algorithm is correct. (a) (10 points) The following algorithm computes r", where I >0 and n > 0, in a more efficient way than multiplying r by itself n - 1 times. Require: r>0, n > 0 1: ans = 1, a = x, P = n 2: while p > 0 do 3: if p is odd then ans = ansa 6: p= (p-1)/2 else a=a*a 9: p=p/2 10: end if 11: end while 12: return ans HINT: Calculate a few iterations by hand. Look for patterns in how ans is related to aP and " (b) (10 points) The following algorithm finds the maximum GCD (Greatest Common Divisor) of a pair of elements in an array, Require: array A of positive integer numbers 1: m = max(A) 2: create array D of size m 3: for i = 1 to length(A) do 4 for j = 1 to m do 5: if Ali] % j = 0 (i.e., jis a divisor of the ith entry of A) then Dj] = Dj] +1 if j != A[i/j (i.e., j is different from the ith entry of A divided by i) then DA[i]/j] = D[Ail/j] + 1 end if 10: end if 11: end for 12: end for 13: return scan D from first index to last, returning the index of the first entry whose value is greater than 1

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Big Data In Just 7 Chapters

Authors: Prof Marcus Vinicius Pinto

1st Edition

B09NZ7ZX72, 979-8787954036

More Books

Students also viewed these Databases questions

Question

Is there a clear hierarchy of points in my outline?

Answered: 1 week ago