Skip to content

Commit

Permalink
Adding Sieve of Eratosthenes in Java
Browse files Browse the repository at this point in the history
  • Loading branch information
Jarvis@LNMIIT committed Aug 9, 2014
1 parent 0c0a911 commit 2837b00
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import java.util.Scanner;
import java.util.*;

public class SieveOfEratosthenes {

public static Stack generatePrimeNumbers(int limit) {

boolean[] arrayOfElements = new boolean[limit+1];

for(int loopingVariable = 2; loopingVariable < arrayOfElements.length; loopingVariable++)
arrayOfElements[loopingVariable] = true;

for(int loopingVariable = 2; loopingVariable*loopingVariable <= limit; loopingVariable++) {

for(int secondryVariable = loopingVariable; secondryVariable*loopingVariable <= limit; secondryVariable++) {

arrayOfElements[loopingVariable*secondryVariable] = false;
}
}

Stack stackOfPrimes = new Stack();

for(int loopingVariable = 2; loopingVariable <= limit; loopingVariable++) {
if (arrayOfElements[loopingVariable]) {
stackOfPrimes.push(loopingVariable);
}
}
return stackOfPrimes;
}

public static void main(String[]args) {

Scanner scannerObject = new Scanner(System.in);

System.out.println("Enter the limit upto which prime numbers are to be generated");
int limit = scannerObject.nextInt();

Stack stackOfPrimes = generatePrimeNumbers(limit);
while(!stackOfPrimes.isEmpty())
System.out.println(stackOfPrimes.pop());
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

import org.junit.Test;
import java.util.Stack;
import static org.junit.Assert.*;

public class SieveOfEratosthenesTest {

@Test
public void TestSieveOfEratosthenes() {
SieveOfEratosthenes objectForSieve = new SieveOfEratosthenes();

Stack stackOfPrimes = objectForSieve.generatePrimeNumbers(20);

assertEquals(stackOfPrimes.pop(),19);
assertEquals(stackOfPrimes.pop(),17);
assertEquals(stackOfPrimes.pop(),13);
assertEquals(stackOfPrimes.pop(),11);
assertEquals(stackOfPrimes.pop(),7);
assertEquals(stackOfPrimes.pop(),5);
assertEquals(stackOfPrimes.pop(),3);
assertEquals(stackOfPrimes.pop(),2);
}
}


0 comments on commit 2837b00

Please sign in to comment.