java 算法题

wxl1990721 2012-03-06 11:31:52
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.

这题 如何解 我刚写那个 要运行好久~~~~(>_<)~~~~

没分了 不能到技术区
...全文
84 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
wxl1990721 2012-03-08
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 zhangqinhappy 的回复:]

Java code

public class Test {
public static void main(String args[]){
int count = 0;
long sum = 0;
int[] array = new int[148933];

for (int i=2……
[/Quote]


你的是对的 O(∩_∩)O~ 2楼的效率不行
机智的呆呆 2012-03-06
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 zhangqinhappy 的回复:]
Java code


public class Test {
public static void main(String args[]){
int count = 0;
long sum = 0;
int[] array = new int[148933];

for ……
[/Quote]
wxl1990721 2012-03-06
  • 打赏
  • 举报
回复
public class Ahelp {
public static void main(String[] args) {
int sum=2;
Ahelp test=new Ahelp();
for (int i = 3; i < 2000000; i+=2) {
System.out.println(i);
if(test.isprime(i)){
sum=sum+i;
}
}
System.out.println(sum);
}
public boolean isprime(int data){//如果data是质数,返回true
boolean re=true;
int con=0;
for (int i = 1; i <=data; i++) {
if(data%i==0){
con++;
}
if(con>2){
re=false;
break;
}
}
return re;
}
}

这是我的代码 不过要执行很久啊。。。。。。。。有没有高效的
zhangqinhappy 2012-03-06
  • 打赏
  • 举报
回复

public class Test {
public static void main(String args[]){
int count = 0;
long sum = 0;
int[] array = new int[148933];

for (int i=2; i<=2000000; i++){
int k = (int)Math.sqrt(i)+1;

for (int j=2; j<=k; j++){
if (i%j == 0)
break;

if (j >= k){

array[0]=2;
count ++;
array[count]=i;
// System.out.print(array[count] +", ");
}
}




}

System.out.println("\nTotal: "+ count);
//System.out.println(array[0] +"第一个素数");


for(int n=0;n<148933;n++){
//System.out.print(array[n]+",");
sum+=array[n];

}
System.out.println();
System.out.println(sum);



}
}



2楼的方法简单。写都写了,就贴上来吧。
java_tanyue 2012-03-06
  • 打赏
  • 举报
回复
public static void main(String[] args) {
int t=0;
for(int i=1;i<=2000000;i++){
for(int j=1;j<2000000;j++){
if(i%j==0&&i!=j){
t=t+i;
}
}
}
System.out.println(t);
}
wxl1990721 2012-03-06
  • 打赏
  • 举报
回复
10以下的素数之和为2+3+5+7=17
求200万以下的素数之和,这个怎么求呢?

23,407

社区成员

发帖
与我相关
我的任务
社区描述
Java 非技术区
社区管理员
  • 非技术区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧