wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Prime Number Generator help Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Prime Number Generator help" Watch "Prime Number Generator help" New topic
Author

Prime Number Generator help

albert abbene
Greenhorn

Joined: Jun 22, 2012
Posts: 4
Hello. My program is supposed to accept #test cases. For each test case, it must accept two integers as a range, then return all prime numbers within the range.
Currently, it prints odd numbers within the range.
So I suspect my problem is within the Boolean i'm using to test whether a number is prime or not.
I pulled the code for the Boolean from this site - http://www.mkyong.com/java/how-to-determine-a-prime-number-in-java/
Maybe I didn't quite understand it, or maybe that's not my real issue.
Any help would be greatly appreciated. Please, and thank you!


In the pipe. 555.
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

You changed the variable names from the code in that link, but you made one little error.

Here it is:

Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38007
    
  22
Beware: what happens if you try to work out whether 6917529027641081857L is prime or not? That is 2^61 + 2^62 + 1.
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 7545
    
  18

albert abbene wrote:Any help would be greatly appreciated. Please, and thank you!

Another little wrinkle for you: Your program accepts ints for its range values, and yet uses a calculation method that takes a long. There's nothing intrinsically wrong with it, but it will slow things down unnecessarily, because arithmetic on longs takes longer (no pun intended). It also wastes space, because your ArrayList has to hold Longs when it could be holding Integers.

Winston


Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
Randall Twede
Ranch Hand

Joined: Oct 21, 2000
Posts: 4340
    
    2

one thing i noticed when i was writing a similar method is it seems unnecessary to check for even numbers


SCJP
Visit my download page
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11160
    
  16

You really only need to test (6*n + 1) and (6*n - 1) for all positive integer values of n, once you get 2 and 3 on your list. That eliminates another 33%.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Prime Number Generator help
 
Similar Threads
Display the prime factors of a number using sets
Need help with Prime number Loop and with boolean statement
Program that takes an int and returns an array of all the prime numbers smaller than that int
counting and primes
Recursive method to print prime factorization of a number