mirror of
https://bitbucket.org/Mattrixwv/projecteulerrust.git
synced 2025-12-06 17:43:58 -05:00
Updated problem 1 algorithm
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
//ProjectEulerRust/src/Problems/Problems1.rs
|
||||
//Matthew Ellison
|
||||
// Created: 06-12-20
|
||||
//Modified: 07-21-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/RustClasses
|
||||
/*
|
||||
@@ -31,26 +31,28 @@ pub fn getDescription() -> &'static str{
|
||||
}
|
||||
|
||||
pub fn solve() -> Answer{
|
||||
let mut fullSum = 0;
|
||||
let mut timer = myClasses::Stopwatch::Stopwatch::new();
|
||||
|
||||
//Start the timer
|
||||
timer.start();
|
||||
//Set through every number < 1000 and see if either 3 or 5 divide it evenly
|
||||
for cnt in 1..1000{
|
||||
//If either divides it then add it to the vector
|
||||
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
|
||||
let fullSum = sumOfProgression(3.0) + sumOfProgression(5.0) - sumOfProgression(3.0 * 5.0);
|
||||
|
||||
//Top the timer
|
||||
timer.stop();
|
||||
|
||||
//Return the answer
|
||||
return Answer::new("The sum of all numbers < 1000 is ".to_string() + &fullSum.to_string(), timer.getString(), timer.getNano());
|
||||
}
|
||||
|
||||
fn sumOfProgression(multiple: f64) -> i64{
|
||||
let numTerms = (999f64 / multiple).floor(); //Get the sum of the progressions of 3 and 5 and remove the sum of progressions of the overlap
|
||||
//The sum of progression formula is (n / 2)(a + l). n = number of terms, a = multiple, l = last term
|
||||
return ((numTerms / 2f64) * (multiple + (numTerms * multiple))) as i64;
|
||||
}
|
||||
|
||||
/* Results:
|
||||
The sum of all numbers < 1000 is 233168
|
||||
It took an average of 893.000 nanoseconds to run this problem through 100 iterations
|
||||
It took an average of 868.000 nanoseconds to run this problem through 100 iterations
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user