Win a copy of Functional Reactive Programming this week in the Other Languages forum!

# prime numbers

Randall Twede
Ranch Hand
Posts: 4481
3
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

Randall Twede
Ranch Hand
Posts: 4481
3
i think i figured it out maybe. i am using longs so the % operator rounds results?

Jeff Verdegan
Bartender
Posts: 6109
6
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
Posts: 4481
3
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
Saloon Keeper
Posts: 15490
43
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.

fred rosenberger
lowercase baba
Bartender
Posts: 12198
35
Randall Twede wrote:it is doing exactly what i told it to

it always does.

Randall Twede
Ranch Hand
Posts: 4481
3
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
Saloon Keeper
Posts: 15490
43
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
Posts: 4481
3
oh....i forgot about the L thanks