Skip to content

Commit

Permalink
Added note on how we compute if a number is a prime.
Browse files Browse the repository at this point in the history
  • Loading branch information
krisfoster committed Dec 16, 2020
1 parent 70c6cd1 commit 46bf282
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
8 changes: 7 additions & 1 deletion 1/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
6 changes: 6 additions & 0 deletions 1/complete/primes/src/main/java/primes/PrimesComputer.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@ public static List<Long> 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);
Expand Down

0 comments on commit 46bf282

Please sign in to comment.