2010: The year we make contact RSS 2.0
# Monday, February 09, 2009

Euler #6 is very straightforward. I was concerned about needing to work with numbers > 2^32, but this was not a factor. I initially set my bound to < max instead of <= max which threw my results off my a small margin (1-99 instead of 1-100). Runtime is < 1 ms, only ~2400 ticks.

using System;
using System.Diagnostics;

namespace Euler6
{
    class Program
    {
        static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            long result = SumDifference(1, 100);
            sw.Stop();
            Console.WriteLine("Runtime was " + sw.ElapsedMilliseconds + " ms");
            Console.WriteLine("Runtime was " + sw.ElapsedTicks +" ticks");
            Console.WriteLine("Sum difference is: " + result);
            Console.ReadLine();

        }

        static long SumDifference(int begin, int end)
        {
            return SquareOfSums(begin, end) - SumOfSquares(begin, end);
        }

        static long SumOfSquares(int begin, int end)
        {
            long returnValue = 0;
            for (int i = begin; i <= end; i++)
            {
                returnValue += Convert.ToInt64(Math.Pow(i,2));
            }
            return returnValue;
        }

        static long SquareOfSums(int begin, int end)
        {
            long returnValue = 0;
            for (int i = begin; i <= end; i++)
            {
                returnValue += i;
            }
            return Convert.ToInt64(Math.Pow(returnValue, 2));
        }
    }
}
Monday, February 09, 2009 11:01:49 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
Bookmark, Tweet, or Share
Comments are closed.
Stackoverflow.com Rep
Flickr stream
Archive
<March 2010>
SunMonTueWedThuFriSat
28123456
78910111213
14151617181920
21222324252627
28293031123
45678910
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
Chris Ballance
Sign In
Statistics
Total Posts: 41
This Year: 6
This Month: 0
This Week: 0
Comments: 9
All Content © 2010, Chris Ballance

Valid XHTML 1.0 Transitional