Files
ProjectEulerJava/Problem6.java

62 lines
2.4 KiB
Java

//ProjectEuler/Java/Problem6.java
//Matthew Ellison
// Created: 03-01-19
//Modified: 03-28-19
//Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
//Unless otherwise listed all non-standard includes are my own creation and available from https://bibucket.org/Mattrixwv/JavaClasses
/*
Copyright (C) 2019 Matthew Ellison
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import mattrixwv.Stopwatch;
public class Problem6{
private static final Integer START_NUM = 1; //The first number that needs to be counted
private static final Integer END_NUM = 100; //The last number that needs to be counted
public static void main(String[] argv){
Stopwatch timer = new Stopwatch(); //SO you can time the algorithm's run time
//Start the timer
timer.start();
//Setup the variables
Long sumOfSquares = 0L; //Holds the sum of the squares of all the numbers
Long squareOfSum = 0L; //Holds the square of the sum of all the numbers
//Run through all numbers and add them to the appropriate sums
for(Integer currentNum = START_NUM;currentNum <= END_NUM;++currentNum){
sumOfSquares += (currentNum * currentNum); //Add the square to the correct variable
squareOfSum += currentNum; //Add the number to the correct variable to squaring later
}
//Squaring the sum that needs it
squareOfSum *= squareOfSum;
//Stop the timer
timer.stop();
//Print the results
System.out.printf("The difference between the sum of the squares and the square of the sum of all numbers from 1-100 is %d\n", Math.abs(sumOfSquares - squareOfSum));
System.out.println("It took " + timer.getStr() + " to run this algorithm");
}
}
/* Results:
The difference between the sum of the squares and the square of the sum of all numbers from 1-100 is 25164150
It took 466.115 microseconds to run this algorithm
*/