Saturday, July 27, 2013

Project Euler Solved using C# : Sum square difference


The sum of the squares of the first ten natural numbers is,
12 + 22 + ... + 102 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)2 = 552 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

Remember Sigma(n) = (n*(n+1))/2
and Sigma(n^2) = (n*(n+1)*(2n+1))/6 

Equating them w.r.t to given problem = Sigma(n)^2 - Sigma(n^2) is

(n * ((n * n) - 1) * ((3 * n) + 2)) / 12

Answer to the Problem is :  25164150
 using System;  
 namespace ProjectEuler  
 {  
   class SquareAndSum  
   {  
     public SquareAndSum(int consquitiveNumbertill)  
     {  
       Console.WriteLine(SqOfSumMinusSumofSq(consquitiveNumbertill));  
     }  
     private long SqOfSumMinusSumofSq(int consquitiveNumbertill)  
     {  
       int n = consquitiveNumbertill;  
       return (n * ((n * n) - 1) * ((3 * n) + 2)) / 12;  
     }  
   }  
 }  

No comments:

Post a Comment