This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Program that takes an int and returns an array of all the prime numbers smaller than that int Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Program that takes an int and returns an array of all the prime numbers smaller than that int" Watch "Program that takes an int and returns an array of all the prime numbers smaller than that int" New topic
Author

Program that takes an int and returns an array of all the prime numbers smaller than that int

mark donner
Greenhorn

Joined: Oct 08, 2011
Posts: 17
I am not sure what is wrong with my code

Basically, for whatever int I put in, I get the biggest prime number (that is smaller than that int), print the amount of times that there are prime numbers in the array.

I very much appreciate anyone who can help me out.

Stefaan Dutry
Ranch Hand

Joined: Sep 17, 2010
Posts: 32

The problem you have is that, when you put the primes into the array, that you, for each of the array indexes keep walking through every value and keep overwriting the previously found one
=> ending up with an array where each index contains the maximum prime below the value entered.




I strongly suggest you have a look at ArrayList.

This way you can add every Integer (or int via autoboxing) you come across to this arrayList instead of having to go through them for the size first and then again for adding them.

If you change your method to return a List of integers, you can also directly loop through all values of the List with an enhanced for loop with autounboxing.



Regards,

Stefaan
mark donner
Greenhorn

Joined: Oct 08, 2011
Posts: 17
Thank you. Very helpful
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Program that takes an int and returns an array of all the prime numbers smaller than that int
 
Similar Threads
Display the prime factors of a number using sets
Recursion-Prime factors
Need help with Prime number Loop and with boolean statement
counting and primes
Recursive method to print prime factorization of a number