#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2003
    Posts
    16
    Rep Power
    0

    is number a prime number program


    I wrote this program to test whether or not a number is prime. I'm just starting out in programming, but when I look at this code, it seems there ought to be a simpler way to do it. Any ideas? (code works, I'm just looking for a better way to do it)

    PHP Code:
    import javax.swing.*;

    class 
    Prime
    {
        public static 
    void main (String args[])
        {
            
    double prime 0;      // this is the number that is tested (to see if it's prime)
            
    double divisor 0;    // 
            
    double counter 1;    // this is the number I divide into prime


            
    prime Double.parseDouble(JOptionPane.showInputDialog("enter potential prime"));

            while ( 
    counter < ( prime ) )  // I only loop it through half of the posibilities because that's all that's necessary
            
    {
                if (
    prime counter == 0)
                {
                    
    divisor prime counter;

                    if (
    divisor != prime)
                    {
                        
    System.out.println(prime " divided by " counter " equals " divisor);
                    }
                }

                
    counter += 1;
            }

            if (
    divisor == prime)
            {
                
    System.out.println(prime " is prime");
            }

        
    System.exit(0);

        }

    Also, rather than supplying a number, I want it to list out all primes within a range. I tried nesting a while loop, and I didn't have much luck. Any thoughts on that aspect? thanks
  2. #2
  3. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2004
    Posts
    1
    Rep Power
    0
    I don't program so you'll have to do the syntax...

    You're close when you define this:

    while ( counter < ( prime / 2 ) ) // I only loop it through half of the posibilities because that's all that's necessary


    But, if a number is not prime, you will find a divisor by the time you reach the square root of the number.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2003
    Posts
    16
    Rep Power
    0
    I'm using integers, so It will only return the square root if it's a perfect square

IMN logo majestic logo threadwatch logo seochat tools logo