feat(problem): 10 - summation of primes

This commit is contained in:
newt 2024-10-09 18:10:09 +01:00
parent f01862dddf
commit 55a16a87a6
8 changed files with 85 additions and 48 deletions

View file

@ -5,11 +5,11 @@
> My solutions to many of Project Euler's problems. > My solutions to many of Project Euler's problems.
All of the solutions here are written in rust. [main.rs](src/main.rs) is the home to my helper command line that can As per the rules of the challenge, I may only publish the solutions to the first 100 problems here, so I will stop after that but still continue the challenge. All of the solutions here are written in rust. [main.rs](src/main.rs) is the home to my helper command line that can scaffold files for me quickly, prefaced with a statement of the problem! As per the rules of the challenge, I may only publish the solutions to the first 100 problems here, so I will stop after that but still continue the challenge.
## Challenge Completion ## Challenge Completion
<!-- completed -->9<!-- completed --> out of 100 public challenges completed. ### <!-- completed -->10<!-- completed --> out of 100 public challenges completed.
- [x] 1 - [Multiples of 3 or 5](src/bin/1.rs) - [x] 1 - [Multiples of 3 or 5](src/bin/1.rs)
- [x] 2 - [Even Fibonacci numbers](src/bin/2.rs) - [x] 2 - [Even Fibonacci numbers](src/bin/2.rs)
@ -20,7 +20,7 @@ All of the solutions here are written in rust. [main.rs](src/main.rs) is the hom
- [x] 7 - [10001st prime](src/bin/7.rs) - [x] 7 - [10001st prime](src/bin/7.rs)
- [x] 8 - [Largest product in a series](src/bin/8.rs) - [x] 8 - [Largest product in a series](src/bin/8.rs)
- [x] 9 - [Special Pythagorean triplet](src/bin/9.rs) - [x] 9 - [Special Pythagorean triplet](src/bin/9.rs)
- [ ] 10 - Summation of primes - [x] 10 - [Summation of primes](src/bin/10.rs)
- [ ] 11 - Largest product in a grid - [ ] 11 - Largest product in a grid
- [ ] 12 - Highly divisible triangular number - [ ] 12 - Highly divisible triangular number
- [ ] 13 - Large sum - [ ] 13 - Large sum

42
src/bin/10.rs Normal file
View file

@ -0,0 +1,42 @@
/*
Problem 10 - Summation of primes
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
*/
// Implementation of the Sieve of Eratosthenes
// https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
fn find_primes(upper_bound: usize) -> Vec<usize> {
let mut mask = vec![true; upper_bound];
let mut primes: Vec<usize> = vec![];
mask[0] = false;
mask[1] = false;
for i in 2..upper_bound {
if mask[i] {
primes.push(i);
let mut j = 2 * i;
while j < upper_bound {
mask[j] = false;
j += i;
}
}
}
return primes;
}
fn sum_of_primes(upper_bound: usize) -> usize {
let primes = find_primes(upper_bound);
return primes.iter().sum::<usize>();
}
fn main() {
let value = sum_of_primes(2000000);
println!("The sum of the primes up until 2000000 is {value}");
}

View file

@ -31,9 +31,9 @@ fn gcd(a: usize, b: usize) -> usize {
return y; return y;
} }
fn first_value_divisible_by(start: usize, end: usize) -> usize { fn first_value_divisible_by(start: usize, end: usize) -> Option<usize> {
if start > end { if start > end {
panic!("You can not start on a value higher than your end value!"); return None;
} }
let mut result: usize = 1; let mut result: usize = 1;
@ -42,11 +42,11 @@ fn first_value_divisible_by(start: usize, end: usize) -> usize {
result = (result * i) / gcd(result, i); result = (result * i) / gcd(result, i);
} }
return result; return Some(result);
} }
fn main() { fn main() {
let number = first_value_divisible_by(1, 20); let number = first_value_divisible_by(1, 20).unwrap();
println!("The smallest number that is divisible by all integers between 1 and 20 is {number}"); println!("The smallest number that is divisible by all integers between 1 and 20 is {number}");
} }

View file

@ -12,9 +12,9 @@ Find the difference between the sum of the squares of the first one hundred natu
const LOWER_BOUND: usize = 1; const LOWER_BOUND: usize = 1;
const UPPER_BOUND: usize = 100; const UPPER_BOUND: usize = 100;
fn sum_of_squares(lower_bound: usize, upper_bound: usize) -> usize { fn sum_of_squares(lower_bound: usize, upper_bound: usize) -> Option<usize> {
if lower_bound > upper_bound { if lower_bound > upper_bound {
panic!("The lower bound must be less than the upper bound!"); return None;
} }
let mut squares: Vec<usize> = vec![]; let mut squares: Vec<usize> = vec![];
@ -23,20 +23,20 @@ fn sum_of_squares(lower_bound: usize, upper_bound: usize) -> usize {
squares.push(i.pow(2)); squares.push(i.pow(2));
} }
return squares.iter().sum(); return Some(squares.iter().sum());
} }
fn square_of_sum(lower_bound: usize, upper_bound: usize) -> usize { fn square_of_sum(lower_bound: usize, upper_bound: usize) -> Option<usize> {
if lower_bound > upper_bound { if lower_bound > upper_bound {
panic!("The lower bound must be less than the upper bound!"); return None;
} }
return ((lower_bound..(upper_bound + 1)).sum::<usize>()).pow(2); return Some(((lower_bound..(upper_bound + 1)).sum::<usize>()).pow(2));
} }
fn main() { fn main() {
let squared_sum = square_of_sum(LOWER_BOUND, UPPER_BOUND); let squared_sum = square_of_sum(LOWER_BOUND, UPPER_BOUND).unwrap();
let summed_squares = sum_of_squares(LOWER_BOUND, UPPER_BOUND); let summed_squares = sum_of_squares(LOWER_BOUND, UPPER_BOUND).unwrap();
let difference = squared_sum - summed_squares; let difference = squared_sum - summed_squares;
println!("For the numbers between {LOWER_BOUND} and {UPPER_BOUND}, the difference between the square of the sum and the sum of the squares is {difference}"); println!("For the numbers between {LOWER_BOUND} and {UPPER_BOUND}, the difference between the square of the sum and the sum of the squares is {difference}");

View file

@ -10,32 +10,25 @@ use std::f64::consts::E;
// Implementation of the Sieve of Eratosthenes // Implementation of the Sieve of Eratosthenes
// https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes // https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
fn find_primes(upper_bound: usize) -> Vec<usize> { fn find_primes(upper_bound: usize) -> Vec<usize> {
let mut values: Vec<bool> = (2..(upper_bound + 1)).map(|_| true).collect(); let mut mask = vec![true; upper_bound];
let mut i = 2; let mut primes: Vec<usize> = vec![];
// Adjust values array mask[0] = false;
while i < (upper_bound as f64).sqrt() as usize { mask[1] = false;
if values[i] {
let mut j = i.pow(2); for i in 2..upper_bound {
if mask[i] {
primes.push(i);
let mut j = 2 * i;
while j < upper_bound { while j < upper_bound {
values[j] = false; mask[j] = false;
j += i; j += i;
} }
} }
i += 1;
} }
// Find the indexes where the values are true
let mut primes: Vec<usize> = vec![];
for i in 0..values.len() {
if values[i] {
primes.push(i);
}
}
return primes; return primes;
} }
@ -52,13 +45,17 @@ fn upper_bound_for_nth_prime(n: usize) -> usize {
return n * (ln_n + ln_n.log(E)).ceil() as usize; return n * (ln_n + ln_n.log(E)).ceil() as usize;
} }
fn nth_prime(n: usize) -> usize { fn nth_prime(n: usize) -> Option<usize> {
if n < 1 {
return None;
}
let primes = find_primes(upper_bound_for_nth_prime(n)); let primes = find_primes(upper_bound_for_nth_prime(n));
return primes[n - 1]; return Some(primes[n - 1]);
} }
fn main() { fn main() {
let number = nth_prime(10001); let number = nth_prime(10001).unwrap();
println!("The 10,001st prime number is {number}"); println!("The 10,001st prime number is {number}");
} }

View file

@ -29,9 +29,9 @@ const NUMBER: &str = "7316717653133062491922511967442657474235534919493496983520
const ADJACENT_DIGITS: usize = 13; const ADJACENT_DIGITS: usize = 13;
fn largest_product(number: &str, adjacent_digits: usize) -> usize { fn largest_product(number: &str, adjacent_digits: usize) -> Option<usize> {
if adjacent_digits > number.len() { if adjacent_digits > number.len() {
panic!("I can not check for the product of {} adjacent digits when there is only {} digits in the number!", adjacent_digits, number.len()); return None;
} }
let mut cursor_index = 0; let mut cursor_index = 0;
@ -68,11 +68,11 @@ fn largest_product(number: &str, adjacent_digits: usize) -> usize {
products.sort(); products.sort();
products.reverse(); products.reverse();
return products[0]; return Some(products[0]);
} }
fn main() { fn main() {
let value = largest_product(NUMBER, ADJACENT_DIGITS); let value = largest_product(NUMBER, ADJACENT_DIGITS).unwrap();
println!("The thirteen adjacent digits in the number that have the greatest product have a product of {value}"); println!("The thirteen adjacent digits in the number that have the greatest product have a product of {value}");
} }

View file

@ -21,21 +21,21 @@ There exists exactly one Pythagorean triplet for which a + b + c = 1000. F
// b = (2an - n^2)/(2a - 2n) // b = (2an - n^2)/(2a - 2n)
// c = n - a - b // c = n - a - b
fn triplet_with_sum(sum: isize) -> (isize, isize, isize) { fn triplet_with_sum(sum: isize) -> Option<(isize, isize, isize)> {
for a in 1..(sum + 1) { for a in 1..(sum + 1) {
let b: isize = ((2 * a * sum) - sum.pow(2)) / (2 * (a - sum)); let b: isize = ((2 * a * sum) - sum.pow(2)) / (2 * (a - sum));
let c: isize = sum - a - b; let c: isize = sum - a - b;
if a.pow(2) + b.pow(2) == c.pow(2) { if a.pow(2) + b.pow(2) == c.pow(2) {
return (a, b, c); return Some((a, b, c));
} }
} }
panic!("A triplet could not be found with the sum {sum}!"); return None;
} }
fn main() { fn main() {
let (a, b, c) = triplet_with_sum(1000); let (a, b, c) = triplet_with_sum(1000).unwrap();
println!("a = {a}, b = {b}, c = {c} // abc = {}", a * b * c); println!("a = {a}, b = {b}, c = {c} // abc = {}", a * b * c);
} }

View file

@ -97,7 +97,7 @@ Problem {} - {}
*/ */
fn main() {{ fn main() {{
println!(\"Hello World!\"); println!(\"Hello World!\");
}}", }}",
problem_number, problem_number,
html_escape::decode_html_entities(&mut title).to_string(), html_escape::decode_html_entities(&mut title).to_string(),
@ -171,12 +171,10 @@ fn main() {{
Ok(()) Ok(())
} }
// todo: runner
fn main() { fn main() {
let value = Value::parse(); let value = Value::parse();
match value.command { match value.command {
Commands::New => new().unwrap(), Commands::New => new().unwrap()
} }
} }