001package de.hdm_stuttgart.mi.sd1.main; 002 003/** 004 * Calculate prime numbers in a yet inefficient way 005 * 006 */ 007public class PrimeNumbers { 008 /** 009 * @param args unused 010 */ 011 public static void main(String[] args) { 012 013 final long startTime = System.currentTimeMillis(); 014 final long numberOfPrimes = findPrimeNumbers(10_000_000); 015 final long endTime = System.currentTimeMillis(); 016 017 System.out.println("Found " + numberOfPrimes + " prime numbers within " + 018 (endTime - startTime) / 1000. + " seconds."); 019 } 020 021 /** 022 * Find all prime numbers up to a given limit. 023 * 024 * @param limit Test all integers from [2, limit] 025 * whether they are prime numbers or not. 026 * @return The number of primes found within [2, limit]. 027 * <dl> 028 <dt>Precondition:</dt> 029 <dd>2 <= limit</dd> 030 </dl> 031 */ 032 public static long findPrimeNumbers(long limit) { 033 long numPrimes = 0; 034 for (int i = 2; i <= limit; i++) { 035 if (isPrime(i)) { 036 numPrimes++; 037 } 038 } 039 return numPrimes; 040 } 041 042 /** 043 * Test, whether a given number is prime. 044 * @param candidate The number to be assessed 045 * @return true if candidate is prime, false otherwise 046 * <dl> 047 <dt>Precondition:</dt> 048 <dd>2 <= candidate</dd> 049 </dl> 050 */ 051 public static boolean isPrime(final long candidate) { 052 for (long i = 2; i * i <= candidate; i++) { // Just test up to square 053 if (0 == candidate % i) { // root of candidate. 054 return false; 055 } 056 } 057 return true; 058 } 059}