Integer square roots 4 Definition: given an integer x>=0, the integer square root (isr) is the largest integer whose square does not exceed x. n Example: isr(4)=2, because 2^2 does not exceed 4, but 3^2 does exceed 4, so 2 is the largest integer whose square does not exceed 4. n Isr(11)=? n 3; 3^2 <11, 4^2>11 n
Integer square roots 4 isr(16)=isr(17)=isr(18)=isr(19)=isr(20)=isr( 21)=isr(22)=isr(23)=isr(24)=4; 4^2=16, 5^2=25 n Thus, we are given x and are looking for an integer y such that y^2<=x && (y+1)^2>x n i. e. , y^2 <= x < (y+1)^2 n Since the square of any real number is nonnegative, no such y exists when x < 0, can’t take the square root of a negative number n
Integer square roots-specification 5 Pre-condition: x > = 0 n Post-condition: y^2 <= x < (y+1)^2 n Design idea: get x, start y at zero, (y^2 <=x), and then y^2 <= x as the program runs, and y is thus the “current approx. ” to isr(x). n Eventually, (y+1)^2 > x, and then y satisfies y^2 <= x < (y+1)^2, i. e. , y is the integer square root of x. n Go to integer_sqrt. java n
Dijkstra--Fast integer square roots 4 Principle: __________________ n| | | ny sqrt(x) z n If y^2<=0, x<z^2, then y+1=z implies y^2 <= x<(y+1)^2 n Each execution of the loop reduces z-y by w, where w > 1 , and thus the algorithm is more efficient than integer square roots. n