Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- boolean[]isPrime = new boolean [N/2+1];
- boolean[]isPrime = new boolean [N+1];
- for (int i = 3; i <= N; i=i+2) {
- isPrime[i] = true;
- }
- for (int i = 3; i <= N; i=i+2) {
- if (isPrime[i]) primes++;
- ...
- }
- Full code:
- public class PrimeSieve {
- public static void main(String[] args) {
- if (args.length < 1) {
- System.out.println("Usage: java PrimeSieve N [-s(ilent)]");
- System.exit(0);
- }
- int N = Integer.parseInt(args[0]);
- // initially assume all odd integers are prime
- boolean[]isPrime = new boolean [N/2+1];
- isPrime[2] = true;
- for (int i = 3; i <= N; i=i+2) {
- isPrime[i] = true;
- }
- int tripCount = 0;
- // mark non-primes <= N using Sieve of Eratosthenes
- for (int i = 3; i * i <= N; i=i+2) {
- // if i is prime, then mark multiples of i as nonprime
- if (isPrime[i]) {
- int j = i * i;
- while (j <= N){
- tripCount++;
- isPrime[j] = false;
- j = j + 2*i;
- }
- }
- }
- System.out.println("Number of times in the inner loop: " + tripCount);
- // count and display primes
- int primes = 0;
- if(N >= 2 ){
- primes = 1;
- }
- for (int i = 3; i <= N; i=i+2) {
- if (isPrime[i]) primes++;
- if (args.length == 2 && args[1].equals("-s"))
- ; // do nothing
- else
- System.out.print(i + " ");
- }
- System.out.println("The number of primes <= " + N + " is " + primes);
- }
- }
- for (int i = 3; i <= N; i=i+2)
- for (int i = 3; i <= N/2; i=i+2)
Add Comment
Please, Sign In to add comment