001package hw3.optional; 002 003public class Primes { 004 005 private static void findPrimes(int nValues) { 006 boolean isPrime = true; 007 008 for (int i = 2; i <= nValues; i++) { 009 isPrime = true; 010 011 for (int j = 2; j < i; j++) { 012 if (i % j == 0) { 013 isPrime = false; 014 break; 015 } 016 } 017 018 if (isPrime) { 019 System.out.println(i); 020 } 021 } 022 } 023 024 025 private static void findPrimesFaster(int nValues) { 026 // PLACE YOUR IMPLEMENTATION HERE 027 System.out.println("The method findPrimesFaster has not been implemented"); 028 } 029 030 031 private static void findPrimesEvenFaster(int nValues) { 032 // PLACE YOUR IMPLEMENTATION HERE 033 System.out.println("The method findPrimesEvenFaster has not been implemented"); 034 } 035 036 037 038 public static void main(String[] args) { 039 040 // Find and print all primes between 0 and 50. 041 042 System.out.println("Running method findPrimes:"); 043 findPrimes(50); 044 045 System.out.println("\nRunning method findPrimesFaster:"); 046 findPrimesFaster(50); 047 048 System.out.println("\nRunning method findPrimesEvenFaster:"); 049 findPrimesEvenFaster(50); 050 051 052 053 // Time how long it takes to find primes. 054 055 long startTime = 0; 056 long endTime = 0; 057 058 059 System.out.print("\n\nTiming method findPrimes:"); 060 startTime = System.currentTimeMillis(); 061 findPrimes(20000); 062 endTime = System.currentTimeMillis(); 063 System.out.println(" " + (endTime-startTime) + " milliseconds"); 064 065 System.out.print("\nTiming method findPrimesFaster:"); 066 startTime = System.currentTimeMillis(); 067 findPrimesFaster(20000); 068 endTime = System.currentTimeMillis(); 069 System.out.println(" " + (endTime-startTime) + " milliseconds"); 070 071 System.out.print("\nTiming method findPrimesEvenFaster:"); 072 startTime = System.currentTimeMillis(); 073 findPrimesEvenFaster(20000); 074 endTime = System.currentTimeMillis(); 075 System.out.println(" " + (endTime-startTime) + " milliseconds"); 076 077 078 System.out.print("\n\nTiming method findPrimes:"); 079 startTime = System.currentTimeMillis(); 080 findPrimes(50000); 081 endTime = System.currentTimeMillis(); 082 System.out.println(" " + (endTime-startTime) + " milliseconds"); 083 084 System.out.print("\nTiming method findPrimesFaster:"); 085 startTime = System.currentTimeMillis(); 086 findPrimesFaster(50000); 087 endTime = System.currentTimeMillis(); 088 System.out.println(" " + (endTime-startTime) + " milliseconds"); 089 090 System.out.print("\nTiming method findPrimesEvenFaster:"); 091 startTime = System.currentTimeMillis(); 092 findPrimesEvenFaster(50000); 093 endTime = System.currentTimeMillis(); 094 System.out.println(" " + (endTime-startTime) + " milliseconds"); 095 } 096 097}