Will Clausen's Website

Categories
WCW

Solution: Project Euler Problem 6

The Problem:

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

My solution (in Java):


// Author: William Clausen
//
// Date: Jan 7, 2013
//
// This program solves Problem 6 form Project Euler.
/* Problem Statement:
 * Find the difference between the sum of the squares of the first one hundred 
 * natural numbers and the square of the sum.
 */


import java.lang.Math; // For squaring numbers

public class Problem6 {

	// Data members to store the number of natural numbers to use,
	// the sum of the squares and the square of the sum.
	public int sumSquare;
	public int squareSum;
	public int Num;
	
	Problem6(int num)
	{
		Num = num;
		sumSquare = 0;
		squareSum = 0;
	}
	
	// Method that solves the problem and returns the result.
	// The heavy lifting is done in the two helper functions,
	// sumSquares(int) and squaredSum(int).
	public int solve()
	{
		sumSquare = sumSquares(Num);
		squareSum = squaredSum(Num);
		
		return squareSum - sumSquare;
	}
	
	// This function computes the sum of the squares of the natural numbers
	// from 1 to num.
	private int sumSquares(int num)
	{
		int sum = 0;
		
		for (int i = 1; i <= num; i++) {
			sum += (int) Math.pow(i,2);
		}
		
		return sum;
	}
	
	// This function computes and returns the square of the sum of the natural 
	// numbers from 1 to num.
	private int squaredSum(int num)
	{
		int totalSum = (num)*(num+1);
		totalSum = totalSum/2;
		totalSum = (int) Math.pow(totalSum, 2);
		
		return totalSum;
	}
}

// Solution: 25164150

Straightforward problem. As always, I love feedback on how this solution could be improved!

Leave a Reply

Your email address will not be published.