Skip to content

Commit ece0ac3

Browse files
2017 primality test performance improvement (#10)
* perf: skip even numbers in primality test -> 2 will always be a factor if even * perf: more efficient square root limit for the primality test
1 parent cd925c2 commit ece0ac3

File tree

1 file changed

+5
-2
lines changed

1 file changed

+5
-2
lines changed

src/year2017/day23.rs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@
5151
//! [`Day 18`]: crate::year2017::day18
5252
use crate::util::parse::*;
5353

54-
/// We only need the vrey first number from the input.
54+
/// We only need the very first number from the input.
5555
pub fn parse(input: &str) -> u32 {
5656
input.unsigned()
5757
}
@@ -69,7 +69,10 @@ pub fn part2(input: &u32) -> usize {
6969
/// Simple [prime number check](https://en.wikipedia.org/wiki/Primality_test)
7070
/// of all factors from 2 to √n inclusive.
7171
fn composite(n: u32) -> Option<u32> {
72-
for f in 2..=n.isqrt() {
72+
if n % 2 == 0 {
73+
return Some(n);
74+
};
75+
for f in (3..).step_by(2).take_while(|m| m * m <= n) {
7376
if n % f == 0 {
7477
return Some(n);
7578
}

0 commit comments

Comments
 (0)