From e50ebb43c61f843871cf15901f7ac8304e41b8dd Mon Sep 17 00:00:00 2001 From: rolv Date: Tue, 8 Jul 2025 12:39:06 +0100 Subject: [PATCH 1/2] perf: skip even numbers in primality test -> 2 will always be a factor if even --- src/year2017/day23.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/year2017/day23.rs b/src/year2017/day23.rs index ee021c4..1b23ece 100644 --- a/src/year2017/day23.rs +++ b/src/year2017/day23.rs @@ -51,7 +51,7 @@ //! [`Day 18`]: crate::year2017::day18 use crate::util::parse::*; -/// We only need the vrey first number from the input. +/// We only need the very first number from the input. pub fn parse(input: &str) -> u32 { input.unsigned() } @@ -69,7 +69,10 @@ pub fn part2(input: &u32) -> usize { /// Simple [prime number check](https://en.wikipedia.org/wiki/Primality_test) /// of all factors from 2 to √n inclusive. fn composite(n: u32) -> Option { - for f in 2..=n.isqrt() { + if n % 2 == 0 { + return Some(n); + }; + for f in (3..=n.isqrt()).step_by(2) { if n % f == 0 { return Some(n); } From 6e39cc3612b22c811336649c1eae46a11c4b7c53 Mon Sep 17 00:00:00 2001 From: rolv Date: Tue, 8 Jul 2025 12:42:24 +0100 Subject: [PATCH 2/2] perf: more efficient square root limit for the primality test --- src/year2017/day23.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/year2017/day23.rs b/src/year2017/day23.rs index 1b23ece..ee51fd7 100644 --- a/src/year2017/day23.rs +++ b/src/year2017/day23.rs @@ -72,7 +72,7 @@ fn composite(n: u32) -> Option { if n % 2 == 0 { return Some(n); }; - for f in (3..=n.isqrt()).step_by(2) { + for f in (3..).step_by(2).take_while(|m| m * m <= n) { if n % f == 0 { return Some(n); }