Unoptimized
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import java.io.*; class PrimeUnoptimized{ public static void main(String args[]) throws IOException{ BufferedReader br = new BufferedReader (new InputStreamReader(System.in)); System.out.print("Up to which number you want to print PN : "); int max = Integer.parseInt(br.readLine()); // now calculate and print the numbers int track = 0; for(int i=1; i<max; i++){ for(int j=1;j<i;j++){ if((i%j) == 0) { if(j!=1 && j!=i){ track=1; } } } if(track==0){ System.out.print(i + ","); } track=0; } } } |
Half Optimized
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import java.io.*; class PrimeOptimizedHalf{ public static void main(String args[]) throws IOException{ BufferedReader br = new BufferedReader (new InputStreamReader(System.in)); System.out.print("Up to which number you want to print PN : "); int max = Integer.parseInt(br.readLine()); // now calculate and print the numbers int track = 0; for(int i=1; i<max; i++){ for(int j=1;j<(i/2);j++){ if((i%j) == 0) { if(j!=1 && j!=i){ track=1; } } } if(track==0){ System.out.print(i + ","); } track=0; } } } |
Optimized
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.io.*; class PrimeOptimized{ public static void main(String args[]) throws IOException{ BufferedReader br = new BufferedReader (new InputStreamReader(System.in)); System.out.print("Up to which number you want to print PN : "); int max = Integer.parseInt(br.readLine()); // now calculate and print the numbers int track = 0; for(int i=1; i<max; i++){ if(((i%2)==0 || (i%3)==0 || (i%5)==0 || (i%7)==0)){ if(i!=2 && i!=3 && i!=5 && i!=7){ track=1; } } if(track==0) System.out.print(i + ","); track=0; } } } |