Skip to content

Commit

Permalink
Optimised solution. Runs in 100 ms.
Browse files Browse the repository at this point in the history
  • Loading branch information
tfpf committed Mar 25, 2024
1 parent c4b5a0b commit f10605a
Showing 1 changed file with 22 additions and 2 deletions.
24 changes: 22 additions & 2 deletions src/solutions/counting_fractions.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,24 @@
pub fn solve() -> i64 {
assert_eq!(303963552391i64, 303963552391);
303963552391
// Calculate Euler's totient of every number up to the limit.
let mut totients = (0..=1000000).collect::<Vec<i64>>();
for num in 2..totients.len() {
if totients[num] == num as i64 {
// This number is prime. The totient of each of its multiples will
// contain the term
// 1/(1 - num)
// in its product expression. Instead of multiply-assigning that
// term, we use an equivalent subtract-assign.
for multiple in (num..totients.len()).step_by(num) {
totients[multiple] -= totients[multiple] / num as i64;
}
}
}

// The number of reduced fractions with a particular denominator is the
// totient of the denominator. Hence, the total number of fractions is the
// sum.
let result = totients[2..].iter().sum();

assert_eq!(result, 303963552391);
result
}

0 comments on commit f10605a

Please sign in to comment.