java代码项目eueler所需的帮助 [英] Help needed for java code project eueler

查看:79
本文介绍了java代码项目eueler所需的帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在项目euler网站上的问题10的代码。它应该找到所有素数低于200万的总和,但给我错误的答案。任何帮助将不胜感激。



  public   class  Problem10 {

public static void main( String [] args){

int sum = 0 ;

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

if (i%k == 0 ){
prime = false;
}
}

如果(素数)
sum + = i;
}

System.out.println(sum);
}

}

解决方案

提示: 2 是一个素数。


你从200万以下的素数列表中删除了2 ...

至于你的代码 - 你应该使用网络(如Google搜索)向他人学习并创建更好的代码来检查数字是否为素数...

https://en.wikipedia.org/wiki/Primality_test [ ^ ]


建议:调试器是您的朋友。滥用它。



没有神奇的方法可以找到错误,只有经验可以告诉你。

通过犯错误获得经验从错误中吸取教训。没有人可以为你获得经验。



只需一个提示,将你的限制从200000改为10,直到你得到正确的结果,然后再进一步。

This is my code for problem 10 on the project euler website. it should find the sum of all the primes below 2 million but gives me the wrong answer. any help would be appreciated.

public class Problem10 {

	public static void main(String[] args) {
		
		int sum = 0;
		
		for(int i = 2;i<2000000;i++){
			boolean prime = true;
			for(int k = 2;k < Math.sqrt(i); k++){
				
				if (i % k == 0){					
					prime = false;
				}
			}
				
			if (prime)
				sum += i;
				}

		System.out.println(sum);
	}

}

解决方案

hint: 2 is a prime number.


You removed 2 from the list of prime numbers under 2 million...
And as for your code - you should use the web (like Google search) to learn from others and create much better code to check if number is prime...
https://en.wikipedia.org/wiki/Primality_test[^]


Advice: The debugger is your friend. Abuse it.

There is no magical way to find errors, only experience can tell you.
And experience is gained by making mistakes and learning from your mistakes. No body can gain experience for you.

Just one hint, change your limit from 200000 to 10 until you get the right result and after this, go further.


这篇关于java代码项目eueler所需的帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆