Created
July 19, 2017 17:06
-
-
Save greymd/d0681e52edfead0af3933b726324bd01 to your computer and use it in GitHub Desktop.
Prime numbers with Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.HashMap; | |
import java.util.Map; | |
class Test { | |
public static void main(String args[]) { | |
int num = 100; | |
Map<Integer, Boolean> list = new HashMap<Integer, Boolean>(); | |
for (int i = 2; i <= num; i++) { | |
list.put(i, true); | |
} | |
for (int i = 2; i*i <= num; i++) { | |
if (list.get(i)) { | |
removeTimes(i, list, num); | |
} | |
} | |
for (int i = 2; i <= num; i++) { | |
if (list.get(i)) { | |
p(i); | |
} | |
} | |
} | |
static void p(int out) { | |
System.out.println(out); | |
} | |
static void removeTimes (int n, Map<Integer, Boolean> list, int num) { | |
for (int i = n*2; i <= num; i+=n) { | |
list.put(i, false); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment