Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Euler problem #10

 
J. Kevin Robbins
Bartender
Pie
Posts: 1793
20
Chrome Firefox Browser jQuery Linux MySQL Database Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another spoiler. This code works for values of 10 and 100, but according to the Euler site, I'm getting the wrong sum for the value of 2000000.

I've spent hours looking at this and can't figure out why it's inconsistent. Can anyone spot the problem?

 
Matthew Brown
Bartender
Posts: 4567
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Overflow?
 
J. Kevin Robbins
Bartender
Pie
Posts: 1793
20
Chrome Firefox Browser jQuery Linux MySQL Database Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nope, the answer I get is 1,179,908,154. An int will hold up to 2,147,483,647.

I'm thinking maybe the square root cast to an int is causing a rounding error which might cause it to falsely identify a prime or two. My next step is to remove the use of the square root and just test all possible divisors.

 
Matthew Brown
Bartender
Posts: 4567
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jk Robbins wrote:Nope, the answer I get is 1,179,908,154. An int will hold up to 2,147,483,647.

Yes, but what if it's already gone all the way around? You're storing the answer in an int - of course it's going to look like it's within range! Just switch to a long, see what happens.
 
J. Kevin Robbins
Bartender
Pie
Posts: 1793
20
Chrome Firefox Browser jQuery Linux MySQL Database Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Doh! Got it!

It didn't even occur to me that it might have wrapped around. I thought it would throw an error if I tried to exceed the max value.

Live and learn. That's why we do these exercises, right?

Thanks!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic