| Author |
prime numbers
|
Randall Twede
Ranch Hand
Joined: Oct 21, 2000
Posts: 4089
|
|
i am getting a strange output from my class
when howMany = 20 i get the following output
Prime Numbers
1
2
3
5
5
5
7
7
7
7
7
9
11
11
11
11
11
11
11
11
11
|
SCJP
|
 |
Randall Twede
Ranch Hand
Joined: Oct 21, 2000
Posts: 4089
|
|
|
i think i figured it out maybe. i am using longs so the % operator rounds results?
|
 |
Jeff Verdegan
Bartender
Joined: Jan 03, 2004
Posts: 5821
|
|
Randall Twede wrote:i think i figured it out maybe. i am using longs so the % operator rounds results?
Not sure what you mean by that, but whatever you mean, no that's not it.
Why does that output surprise you? What would you expect instead? You should add print statements or use a debugger so you can see what's actually happening?
Also note that when checking for divisors of X, you only need to go up to the square root of X.
|
 |
Randall Twede
Ranch Hand
Joined: Oct 21, 2000
Posts: 4089
|
|
thats right that is not the problem. i will try some System.out.println
you are also correct that i dont have to loop so many times
i see the problem now. it is doing exactly what i told it too
thanks for the tip about only needing to go up to the square root
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12907
|
|
Randall Twede wrote:it is doing exactly what i told it too
Yes, that's the biggest problem that people have with computers. They always do exactly what you tell them to do, not what you intended them to do.
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
fred rosenberger
lowercase baba
Bartender
Joined: Oct 02, 2003
Posts: 9942
|
|
Randall Twede wrote:it is doing exactly what i told it to
it always does.
|
Never ascribe to malice that which can be adequately explained by stupidity.
|
 |
Randall Twede
Ranch Hand
Joined: Oct 21, 2000
Posts: 4089
|
|
ok, i solved that one. now i am trying to solve problem3 a projectEuler.net
here is my solution of original problem
the new problem is this: What is the largest prime factor of the number 600851475143 ?
even using longs the number is too big. and Math.sqrt() requires a double and the number is too big
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12907
|
|
600851475143 does fit in a long, but if you write it in source code you have to put an "L" at the end of it: long value = 600851475143L;
If you don't, Java is going to interpret 600851475143 as an int literal instead of a long, and it's going to tell you the number is too big to fit in an int.
To solve this problem, you should do something smarter than checking if all numbers smaller than 600851475143 are primes. That's the trick of this Project Euler exercise!
|
 |
Randall Twede
Ranch Hand
Joined: Oct 21, 2000
Posts: 4089
|
|
oh....i forgot about the L thanks
|
 |
 |
|
|
subject: prime numbers
|
|
|