Raise number to the specified power

       /// <summary>
        /// An O(n log2 n) time algorithm for raise number to the specified power
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            Console.WriteLine(Pow(2, 10));
            Console.ReadKey();
        }
        /// <summary>
        /// Returns a specified number raised to the specified power
        /// </summary>
        /// <param name="number">A number to be raised to a power. </param>
        /// <param name="power">A number that specifies a power. </param>
        /// <returns>The number x raised to the power y.</returns>
        private static int Pow(int number, int power)
        {
            int result = 1;
            int even = number;
            while(power > 0)
            {
                if ((power % 2) == 0)
                {
                    even *= even;
                    power /= 2;
                }
                else
                {
                    result *= even;
                    power–;
                }
            }
            return result;
        }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s