The answer to life, the universe and everything is famously known to be 42, as stated in Douglas Adams' book "The Hitchhiker's Guide to the Galaxy". To compute this in C#, you can use recursion to implement a binary search algorithm to find the answer.
main.cs781 chars46 lines
The Answer
method uses a binary search algorithm to guess the answer. It starts by setting the lower bound to 0 and the upper bound to the maximum value of an integer. It then repeatedly guesses the middle point between the lower and upper bounds, and asks if the guess is the answer. If the guess is too high, it sets the upper bound to one less than the guess. If the guess is too low, it sets the lower bound to one more than the guess. This process continues until the answer is found.
The AskQuestion
method simply compares the guess to the answer, and returns -1 if the guess is too low, 0 if the guess is correct, and 1 if the guess is too high.
To use this code, simply call the Answer
method:
main.cs38 chars2 lines
This will output the answer to the console. Enjoy and don't forget to have fun!
gistlibby LogSnag