File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Need help with Prime number Loop and with boolean statement Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Need help with Prime number Loop and with boolean statement" Watch "Need help with Prime number Loop and with boolean statement" New topic
Author

Need help with Prime number Loop and with boolean statement

Kwasi Roberts
Greenhorn

Joined: May 28, 2011
Posts: 4
Can someone tell me where I'm going wrong here in making this read all prime numbers
import java.util.*;

Here is my original code


Here is the code where I was asked to combine a while loop with a boolean statement. I need help on both.



[Edit: put code between [code] and [/code] ubb code blocks]
Andrew Monkhouse
author and jackaroo
Marshal Commander

Joined: Mar 28, 2003
Posts: 11278
    
  59

For the first class:
  • What is the definition of a Prime number? How are you handling the two conditions to validate that it is a prime?
  • What are you trying to do in lines 20 - 22?


  • The Sun Certified Java Developer Exam with J2SE 5: paper version from Amazon, PDF from Apress, Online reference: Books 24x7 Personal blog
    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 36474
        
      16
    You are both mistaken using ½ the number as the limit for testing whether it is prime. You ought to use √number. You also should use a Sieve of Eratosthenes to populate a boolean array and that will tell you whether a number is prime or not. Much faster and efficient than using the % operator. If you look in the Wikipedia article which appears from that link, there is the Sieve of Euler, too.
    Andrew Monkhouse
    author and jackaroo
    Marshal Commander

    Joined: Mar 28, 2003
    Posts: 11278
        
      59

    vinayak jog - thank you for replying, however at CodeRanch we work on the theory that we want to teach people how to solve the problems themselves. Complete solutions don't lend themselves to that - the learning experience is removed.

    I therefore removed your response.
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: Need help with Prime number Loop and with boolean statement
     
    Similar Threads
    Happy/unhappy numbers
    what's wrong with the for-each
    when i run my virtual machine just keeps going, but no output.
    Project Euler : Problem 23
    Program that takes an int and returns an array of all the prime numbers smaller than that int