compute the answer to life, the universe and everything in csharp

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.cs
using System;

public class Universe
{
    public static int Answer()
    {
        int low = 0;
        int high = int.MaxValue;

        while (true)
        {
            int guess = (low + high) / 2;
            int result = AskQuestion(guess);

            if (result == 0)
            {
                return guess;
            }
            else if (result < 0)
            {
                high = guess - 1;
            }
            else
            {
                low = guess + 1;
            }
        }
    }

    private static int AskQuestion(int guess)
    {
        if (guess == 42)
        {
            return 0;
        }
        else if (guess < 42)
        {
            return -1;
        }
        else
        {
            return 1;
        }
    }
}
781 chars
46 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.cs
Console.WriteLine(Universe.Answer());
38 chars
2 lines

This will output the answer to the console. Enjoy and don't forget to have fun!

gistlibby LogSnag