求1~10000之间的素数个数
首先存储1~100内的素数,然后在据此计算1~10000内素数以及个数
- package program;
- import java.util.Arrays;
- public class suShu100 {
- static boolean[] flag = new boolean[101];
- static int[] arrs = new int[100];
- static int num = 0;
- public static void main(String[] args) {
- // 1 存储100以内的素数
- GenPrime();
- System.out.println(Arrays.toString(arrs));
- System.out.println(num);
- // 2 求10000以内的素数
- int count = 0;
- for (int i = 2; i <= 10000; i++) {
- if (IsPrime(i)) {
- count++;
- // System.out.print(i + " ");
- // if (count % 10 == 0) {
- // System.out.println("");
- // }
- }
- }
- System.out.println(count);
- }
- private static boolean IsPrime(int s) {
- int num2 = 0;
- int k = 0;
- if (s <= 100) {
- if (flag[s]) {
- return true;
- } else {
- return false;
- }
- }
- while (arrs[k] * arrs[k] <= s && k < num) {
- if (s % arrs[k] == 0) {
- return false;
- }
- k++;
- }
- return true;
- }
- private static void GenPrime() {
- int s = 0;
- int j = 0;
- for (int i = 0; i < flag.length; i++) {
- flag[i] = true;
- }
- flag[0] = false;
- flag[1] = false;
- for (int i = 2; i <= 100; i++) {
- if (flag[i]) {
- arrs[s++] = i;
- }
- j = 2 * i;
- while (j <= 100) {
- flag[j] = false;
- j = j + i;
- }
- }
- num = s;
- }
- }
结果:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
25
1229
posted on 2017-07-19 11:33 WenjieWangFlyToWorld 阅读(649) 评论(0) 编辑 收藏 举报