Created
February 25, 2025 10:55
-
-
Save pooya-raz/59aa46460f72f994f204a861c7342b4b to your computer and use it in GitHub Desktop.
Bob Martin prime generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.hollandandbarrett.tpl.literatePrimes; | |
public class PrimeGenerator3 { | |
private static int[] primes; | |
private static int[] primeMultiples; | |
private static int lastRelevantMultiple; | |
private static int primesFound; | |
private static int candidate; | |
// Lovely little algorithm that finds primes by predicting | |
// the next composite number and skipping over it. That prediction | |
// consists of a set of prime multiples that are continuously | |
// increased to keep pace with the candidate. | |
public static int[] generateFirstNPrimes(int n) { | |
initializeTheGenerator(n); | |
for (candidate = 5; primesFound < n; candidate += 2) { | |
increaseEachPrimeMultipleToOrBeyondCandidate(); | |
if (candidateIsNotOneOfThePrimeMultiples()) { | |
registerTheCandidateAsPrime(); | |
} | |
} | |
return primes; | |
} | |
private static void initializeTheGenerator(int n) { | |
primes = new int[n]; | |
primeMultiples = new int[n]; | |
lastRelevantMultiple = 1; | |
// prime the pump. (Sorry, couldn't resist.) | |
primesFound = 2; | |
primes[0] = 2; | |
primes[1] = 3; | |
primeMultiples[0] = -1;// irrelevant | |
primeMultiples[1] = 9; | |
} | |
private static void increaseEachPrimeMultipleToOrBeyondCandidate() { | |
if (candidate >= primeMultiples[lastRelevantMultiple]) | |
lastRelevantMultiple++; | |
for (int i = 1; i <= lastRelevantMultiple; i++) | |
while (primeMultiples[i] < candidate) | |
primeMultiples[i] += 2 * primes[i]; | |
} | |
private static boolean candidateIsNotOneOfThePrimeMultiples() { | |
for (int i = 1; i <= lastRelevantMultiple; i++) | |
if (primeMultiples[i] == candidate) | |
return false; | |
return true; | |
} | |
private static void registerTheCandidateAsPrime() { | |
primes[primesFound] = candidate; | |
primeMultiples[primesFound] = candidate * candidate; | |
primesFound++; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment