日期:2014-05-20  浏览次数:20843 次

素数
有1到N   这样N个数
找出里面的质数的个数   计为A
求根号N   计为B
求A/B     不用做图形界面
要求实现输入N   自动计算A   B   A/B   并显示  

诚心求问   第一次提问

先谢谢大家了

------解决方案--------------------
不知道干吗用....

import java.util.*;

public class Sieve {
public static void main(String[] s) {
int n = 2000000;
int count = sieveCount(n);
double j = Math.sqrt(n);
double result = count/j;
System.out.println(count);
System.out.println(j);
System.out.println(result);
}

public static int sieveCount(int n) {
BitSet b = new BitSet(n + 1);
int count = 0;
int i;
for (i = 2; i <= n; i++)
b.set(i);
i = 2;
while (i * i <= n) {
if (b.get(i)) {
count++;
int k = 2 * i;
while (k <= n) {
b.clear(k);
k += i;
}
}
i++;
}
while (i <= n) {
if (b.get(i))
count++;
i++;
}
return count;
}
}
------解决方案--------------------
for example
void fun (int n) {
int a = 0;
double c, b = Math.sqrt(n);
boolean b;
for (int i=2; i <n; i+) {
b = true;
for (int j=2; j <=(int)Math.sqrt(i); j++) {
if (i%j == 0) {
b = false;
break;
}
}
if (b) {
a++;
}
}
c = a/b;
System.out.printf( "A=%d, B=%.2f, C=%.2f ", a, b, c);
}


------解决方案--------------------
爆汗 ,刚才的贴错了,请无视!-_-!!
import java.math.*;
public class SeekPrime {
public static void main(String[] args) {
SeekPrime sp = new SeekPrime();
int n = 50;
int a = sp.numberOfPrime(n);
double b = Math.sqrt(n);
double result = a/b;
System.out.println( "counter : " + a);
System.out.println(result);
}
public int numberOfPrime(int n) {
int counterOfPrime = 0;
for(int i = 1;i <= n;i++) {
boolean isPrime = true;
for(int j = 2;j < i;j++) {
if(i%j == 0) {
isPrime = false;
}
}
if(isPrime) {
System.out.println(i);
counterOfPrime++;
}
}
return counterOfPrime;
}
}

运行结果:
1
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
counter : 16
2.262741699796952