Created
June 20, 2015 00:04
-
-
Save chandu-io/0dd3ff1d9264a6ea6c82 to your computer and use it in GitHub Desktop.
java :: Prime series generator (prime number)
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
| 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