This is an intro to Java question. Please include pseudo code for better understanding. I am hoping to use this to do some reviewing. We are mainly focusing on input and output declarations and invoking API methods.
Problem 6: Log It (10 points) Use API (Data Structure Algorithms) High-Low is a simple number guessing game where one player thinks of a random integer number between 0 to some maximum value and another player attempts to guess that number. With each turn, player one tells player two whether their guess was correct, too high, or too low. The optimal strategy for playing this game is to select the middle value between the largest and smallest possible numbers. In Computer Science, this strategy is called a Binary Search Algorithm. Binary search algorithms eliminate half the possible search space with each pass. Your task is to determine the maximum number of tries it takes to guess the number correctly using the Binary Search algorithm. This can be determined by taking the log2 value of the maximum number. Since this result represents the max number of guesses round any fractional result up to the next highest integer.
Facts
● Log2(number) is calculated using guesses = log (2) log (max number)
● Java Math class contains log and ceil methods ○ https://docs.oracle.com/javase/10/docs/api/java/lang/Math.html
● Your solution should have a main method.
● Use Scanner for input & Use System.out for output!
Input The first line of input represents the number of test cases. Each case contains one positive integer number that represents the maximum numbered value in the High-Low game.
Output Print the integer that represents the maximum number of guesses it would take to find the secret number using binary search algorithm.
Sample Input
4
10
100
1000
10000
Sample Output
4
7
10
14
import java.util.Scanner; public class LogMain { public static int log(int num) { double n = num; int count = 0; while (n > 1) { ++count; n /= 2; } return count; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); for (int i = 0; i < n; i++) { System.out.println(log(in.nextInt())); } } }
Get Answers For Free
Most questions answered within 1 hours.