In: Computer Science
3. What does mystery2 compute on an input n? Please explain how you found this. thanks!
public static int problem1(int n) {
int begin = 0;
int end = n+1;
while (begin+1 < end){
int mid = (begin+end)/2;
if(112*mid <= n){
begin = mid;
}
else{
end = mid;
}
}
return begin;
}
ANSWER: I created a program to test your method we have put n value is higher to get the result greater than 0 because this method always returning begin value which 0 and it is updating when if condition becomes true. below is the explanation in the code please like it.
CODE:
public class Test
{
public static int problem1(int n) {
int begin = 0;// here begin is initialized with 0
int end = n+1; // end vaue will be 1 more than n
while (begin+1 < end){ // this while will start from 1 to end means n+1
int mid = (begin+end)/2; // mid value for each iteration
if(112*mid <= n){ // condition which will be true if mid*112 > n then only begin will be equal to mid
begin = mid;
}
else{
end = mid; // otherwise end will be mid
}
}
return begin; // returning the begin value always
}
public static void main(String [] args)
{
System.out.println("problem1 value when n=500:
"+problem1(500));
}
}
output: