mirror of
https://bitbucket.org/Mattrixwv/projecteulerjava.git
synced 2025-12-06 17:13:58 -05:00
Updated problem 1 algorithm
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
//ProjectEulerJava/src/main/java/mattrixwv/ProjectEuler/Problems/Problem1.java
|
||||
//Matthew Ellison
|
||||
// Created: 03-01-19
|
||||
//Modified: 08-27-20
|
||||
//Modified: 10-26-20
|
||||
//What is the sum of all the multiples of 3 or 5 that are less than 1000
|
||||
//Unless otherwise listed all non-standard includes are my own creation and available from https://bibucket.org/Mattrixwv/JavaClasses
|
||||
/*
|
||||
@@ -51,15 +51,8 @@ public class Problem1 extends Problem{
|
||||
//Start the timer
|
||||
timer.start();
|
||||
|
||||
//Check every number < 1000 to see if it is a multiple of 3 or 5. If it is add it to the running sum
|
||||
for(int cnt = 1;cnt <= TOP_NUM;++cnt){
|
||||
if((cnt % 3) == 0){
|
||||
fullSum += cnt;
|
||||
}
|
||||
else if((cnt % 5) == 0){
|
||||
fullSum += cnt;
|
||||
}
|
||||
}
|
||||
//Get the sum of the progressions of 3 and 5 and remove the sum of progressions of the overlap
|
||||
fullSum = sumOfProgression(3) + sumOfProgression(5) - sumOfProgression(3 * 5);
|
||||
|
||||
//Stop the timer
|
||||
timer.stop();
|
||||
@@ -73,6 +66,12 @@ public class Problem1 extends Problem{
|
||||
super.reset();
|
||||
fullSum = 0;
|
||||
}
|
||||
//Gets the sum of the progression of the multiple
|
||||
private int sumOfProgression(double multiple){
|
||||
double numTerms = Math.floor((double)TOP_NUM / multiple); //This gets the number of multiples of a particular number that is < MAX_NUMBER
|
||||
//The sum of progression formula is (n / 2)(a + l). n = number of terms, a = multiple, l = last term
|
||||
return (int)((numTerms / 2.0) * (multiple + (numTerms * multiple)));
|
||||
}
|
||||
//Gets
|
||||
//Returns the result of solving the problem
|
||||
@Override
|
||||
@@ -94,5 +93,5 @@ public class Problem1 extends Problem{
|
||||
|
||||
/* Results:
|
||||
The sum of all numbers < 1000 is 233168
|
||||
It took an average of 27.833 microseconds to run this problem through 100 iterations
|
||||
It took an average of 298.000 nanoseconds to run this problem through 100 iterations
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user