X to the power of X (X^X)

One of my sons asked an interesting question: what number raised to itself equals to 25? In other words, he wanted to find X such that X^X = 25.

I decided to write a simple program (no GAI for a change, just vintage coding) to do that. The key observations here are:

1/ X^X is continuous in the real domain

2/ It grows monotonically 

3/ It grows very fast

With that in mind, the solution is a binary search. The lower bound is 1, the upper bound can be found quickly by doubling the number, then we perform a standard binary search (some nuances there just because we're dealing with floating-point numbers). Complexity stays around Log(Log(N)), hence very fast. Code is down below, cheers. Oh... and the answer to my son is the following: 2.96321964263916

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Exp
{
    internal class Program
    {
        static void Main(string[] args)
        {
            double input = Double.Parse(args[0]);
            Process(input);
        }

        static void Process(double n)
        {
            double lowerBound = 1;
            double upperBound = 1;

            double val = Math.Pow(upperBound, upperBound);
            while (val < n)
            {
                upperBound *= 2;
                val = Math.Pow(upperBound, upperBound);
            }

            double ZERO = 0.00001;
            int maxInt = 10000;
            double mid = 1;
            while (lowerBound < upperBound && maxInt > 0)
            {
                mid = (lowerBound + upperBound) / 2;
                val = Math.Pow(mid, mid);

                if (Math.Abs(n - val) <= ZERO)
                {
                    break;
                }
                else if (val > n)
                {
                    upperBound = mid;
                }
                else
                {
                    lowerBound = mid;
                }
                maxInt--;
            }
            Console.WriteLine("{0}^{0} ~= {1}", mid, n);
        }
    }
}

Comments

Popular posts from this blog

Standard Priority Queue IX: Vowels Frequency

The Power Sum, a recursive problem by HackerRank

Binary Search to Find Next Greater Element V