Loop is an important construct in building programs. Construct correct "while" loops to solve the following problems. Write all the programs in Java. Please write the loop invariant as comments in your code. Justify your code using the loop invariant and the loop condition. Test your code and verify it works before submitting your code to Canvas.
Note that your Java file name needs to be the same as your public
class name in the file. Otherwise, Java reports error.
Solution
public class Gcd {
public static int gcd(int a, int b)
{
if (a == 0) return b;
if (b == 0) return a;
// {I: gcd(a, b) == gcd(a0, b0), where a0 and b0
// are inital values of a and b }
while (a != b)
{
if (a > b)
a = a - b;
else
b = b - a;
}
return a;
}
public static void main(String[] args)
{
System.out.println(gcd(35, 21));
System.out.println(gcd(16, 40));
}
}
public class Reverse {
public static int reverse(int x)
{
int r = 0;
// {I: x is the value of the part that has not been reversed
// r is the reversed value of processed part }
while (x != 0)
{
int lowest_digit = x % 10;
x = x / 10;
r = r * 10 + lowest_digit;
}
return r;
}
public static void main(String[] args)
{
System.out.println(reverse(123456));
System.out.println(reverse(12340));
System.out.println(reverse(12034));
}
}
public class Sqrt {
public static int sqrt(int x)
{
int a = 0;
int b = x;
// {I: sqrt(x) is always in [a, b] }
while (a != b)
{
int c = (a+b)/2;
if (c*c <= x && (c+1)*(c+1) > x)
return c;
if (c*c > x)
b = c - 1;
else
a = c + 1;
}
return a;
}
public static void main(String[] args)
{
System.out.println(sqrt(101));
System.out.println(sqrt(64));
System.out.println(sqrt(0));
}
}