• Post Reply Bookmark Topic Watch Topic
  • New Topic

Project Euler problem 10  RSS feed

 
dhrubo bhattacharjee
Greenhorn
Posts: 20
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Everyone,

I was trying to solve the problems in Project Euler. I tried to solve the Problem 10 which says :

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.


The following is my implementation :





This is the following output I am getting :



which is wrong.My code works fine for small number such as 10.

Can anyone please let me know where I am going wrong?

 
dhrubo bhattacharjee
Greenhorn
Posts: 20
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I figured it out. Changing the sum to long did the trick.



Output :



Thanks


However the another question I have is regarding the performance.A few online tutorials use a boolean array to set all the values as true or false whereas I am using an integer array and setting the values to 0 and 1 initially.Does this make any difference in the performance?
 
Campbell Ritchie
Marshal
Posts: 55772
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why are you using the keyword static so often? Why have you closed System.in (line 10)? Why are you not using booleans? What have you got for the inputs 0 and 1? Are they prime? Why are you using an int for the sum? By the time you have several thousand numbers > 1000000, you will suffer an arithmetic overflow. Make sum a long. Don't loop filling the array with the same value throughout. Use Arrays#fill.
 
Campbell Ritchie
Marshal
Posts: 55772
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
dhrubo bhattacharjee wrote:I figured it out. Changing the sum to long did the trick. . . . However the another question I have is regarding the performance.A few online tutorials use a boolean array to set all the values as true or false whereas I am using an integer array and setting the values to 0 and 1 initially.Does this make any difference in the performance?
Well done sorting it out, while I was trying your code to find the problem
The int[] is not at all good code; you should use boolean[]s. You will have to test the performance; I think any difference between the two kinds of array will be negligible. Somebody else tried a solution to that puzzle here a few months ago; you should try their data structure too, and see how it does for performance. They used this and achieved fast performance.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!