From 46bf28286ac532d627c09f814f61c43de057ba08 Mon Sep 17 00:00:00 2001 From: Kris Foster Date: Wed, 16 Dec 2020 13:03:04 +0000 Subject: [PATCH] Added note on how we compute if a number is a prime. --- 1/README.md | 8 +++++++- .../primes/src/main/java/primes/PrimesComputer.java | 6 ++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/1/README.md b/1/README.md index 1a8d580..813def8 100644 --- a/1/README.md +++ b/1/README.md @@ -99,7 +99,13 @@ public class PrimesComputer { .boxed() .collect(Collectors.toList()); } - + + /** + * If n is not a prime, then n = a * b (some a & b) + * Both a and b can't be larger than sqrt(n), or the product of them would be greater than n + * One of the factors has to be smaller than sqrt(n). + * So, if we don't find any factors by the time we get to sqrt(n), then n must be prime + */ public static boolean isPrime(long n) { return LongStream.rangeClosed(2, (long) Math.sqrt(n)) .allMatch(i -> n % i != 0); diff --git a/1/complete/primes/src/main/java/primes/PrimesComputer.java b/1/complete/primes/src/main/java/primes/PrimesComputer.java index c92bf61..30d54f6 100644 --- a/1/complete/primes/src/main/java/primes/PrimesComputer.java +++ b/1/complete/primes/src/main/java/primes/PrimesComputer.java @@ -21,6 +21,12 @@ public static List primeSequence(long min, long max) { .collect(Collectors.toList()); } + /** + * If n is not a prime, then n = a * b (some a & b) + * Both a and b can't be larger than sqrt(n), or the product of them would be greater than n + * One of the factors has to be smaller than sqrt(n). + * So, if we don't find any factors by the time we get to sqrt(n), then n must be prime + */ public static boolean isPrime(long n) { return LongStream.rangeClosed(2, (long) Math.sqrt(n)) .allMatch(i -> n % i != 0);