Primes.java

1
package findPrimes; 2 3 public class Primes { 4 5 private final static int MAXPRIMES = 100; 6 7 private boolean isDvisible(int a, int b) { 8 if ((b % a) == 0) { 9 return true; 10 } 11 return false; 12 } 13 14 public String printPrimes(int n) { 15 String prime = ""; 16 int curPrime; //Value currently considered for primeness 17 int numPrimes; // Number of primes found so far; 18 boolean isPrime; //Is curPrime prime? 19 int[] primes = new int[MAXPRIMES];// The list of primes. 20 21 // Initialize 2 into the list of primes. 22 primes[0] = 2; 23 numPrimes = 1; 24 curPrime = 2; 25 while(numPrimes < n) { 26 curPrime++; // next number to consider... 27 isPrime = true; 28 for(int i = 0; i <= numPrimes; i++ ) { 29 //for each previous prime. 30 if(isDvisible(primes[i],curPrime)) { 31 //Found a divisor, curPrime is not prime. 32 isPrime = false; 33 break; 34 } 35 } 36 if(isPrime) { 37 // save it! 38 primes[numPrimes] = curPrime; 39 numPrimes++; 40 41 } 42 }// End while 43 44 // print all the primes out 45 for(int i = 0; i < numPrimes; i++) { 46 //System.out.println("Prime: " + primes[i] ); 47 Integer inte = new Integer(primes[i]); 48 prime += inte.toString(); 49 } 50 return prime; 51 52 }// End printPrimes. 53 54 }
 Test case
PrimePathConverage

1
package findPrimes; 2 3 import static org.junit.Assert. *; 4 5 import org.junit.Before; 6 import org.junit.Test; 7 8 public class PrimePathConverage { 9 10 private Primes primes; 11 @Before 12 public void setUp() { 13 primes = new Primes(); 14 } 15 16 @Test 17 public void test1() { 18 // [1,2,9,10,12] 19 assertEquals("", primes.printPrimes(1)); 20 } 21 22 @Test 23 public void test2() { 24 assertEquals("23", primes.printPrimes(3)); 25 } 26 27 28 }

posted on 2018-03-25 17:59  znnby1997  阅读(318)  评论(0编辑  收藏  举报