Updated problem 1 algorithm

This commit is contained in:
2020-10-26 14:44:39 -04:00
parent b1beedcab4
commit 9d78742f57

View File

@@ -1,7 +1,7 @@
//ProjectEuler/ProjectEulerCS/src/Problems/Problem1.cs //ProjectEuler/ProjectEulerCS/src/Problems/Problem1.cs
//Matthew Ellison //Matthew Ellison
// Created: 08-14-20 // Created: 08-14-20
//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 //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/CSClasses //Unless otherwise listed all non-standard includes are my own creation and available from https://bibucket.org/Mattrixwv/CSClasses
/* /*
@@ -22,6 +22,9 @@
*/ */
using System;
namespace ProjectEulerCS.Problems{ namespace ProjectEulerCS.Problems{
public class Problem1 : Problem{ public class Problem1 : Problem{
//Variables //Variables
@@ -64,15 +67,8 @@ namespace ProjectEulerCS.Problems{
//Start the timer //Start the timer
timer.Start(); 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 //Get the sum of the progressions of 3 and 5 and remove the sum of progressions of the overlap
for (int cnt = 1; cnt <= TOP_NUM; ++cnt){ fullSum = SumOfProgression(3) + SumOfProgression(5) - SumOfProgression(3 * 5);
if ((cnt % 3) == 0){
fullSum += cnt;
}
else if ((cnt % 5) == 0){
fullSum += cnt;
}
}
//Stop the timer //Stop the timer
timer.Stop(); timer.Stop();
@@ -85,10 +81,15 @@ namespace ProjectEulerCS.Problems{
base.Reset(); base.Reset();
fullSum = 0; fullSum = 0;
} }
private int SumOfProgression(double multiple){
double numTerms = Math.Floor(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)));
}
} }
} }
/* Results: /* Results:
The sum of all numbers < 1000 is 233168 The sum of all numbers < 1000 is 233168
It took an average of 1.430 microseconds to run this problem through 100 iterations It took an average of 1.351 microseconds to run this problem through 100 iterations
*/ */