Skip to content

Instantly share code, notes, and snippets.

@chandu-io
Created June 20, 2015 00:04
Show Gist options
  • Select an option

  • Save chandu-io/0dd3ff1d9264a6ea6c82 to your computer and use it in GitHub Desktop.

Select an option

Save chandu-io/0dd3ff1d9264a6ea6c82 to your computer and use it in GitHub Desktop.
java :: Prime series generator (prime number)
import java.util.*;
public class PrimeSeries {
public static void main(String[] tcs) throws Exception {
if (tcs.length < 1) {
log("Invalid limit. Terminating...");
return;
}
long limit = Long.parseLong(tcs[0]);
generatePrimes(limit);
}
public static void generatePrimes(long limit) {
log("2,3");
List<Long> primes = new ArrayList<Long>(Arrays.asList((long) 2, (long) 3));
long incr = 2, a = 3 + incr;
while (a <= limit) {
long sqrt = (long) Math.sqrt(a);
boolean isPrime = true;
for (long prime : primes) {
if (prime > sqrt) {
break;
}
if (a % prime == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
primes.add(a);
log(",%s", a);
}
a += incr;
}
}
public static void log(String text, Object... args) {
System.out.print(String.format(text, args));
}
public static void logn(String text, Object... args) {
System.out.println(String.format(text, args));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment