Skip to main content
GameDev.net gamedev.net
🔒 Locked

Java problem - Prime numbers

Started by DribbleDribble Sep 20, 2010 at 5:36 PM 10 replies 1.7k views
Original Post
DribbleDribble
DribbleDribble
So, im making a program that allows you to enter a variable (n) and tells you whether it is a variable or not. Im having a tad bit of trouble with it but I know its probably a stupis mistake again.
Hope you guys can help

Heres my code so far:

import java.util.*;
import javax.swing.*;
import java.math.*;

class lab4p2
{
public boolean isPrime(int n) {
Scanner scanner = new Scanner(System.in);
System.out.print("What is N?");
n = scanner.nextInt();
if (n < 2 || n%2 == 0) {
if (n == 2)
return true;
else
return false;
}
for (int i = 3; i <= Math.sqrt(n);i = i+2) {
if (n%i == 0)
return false;
}
return true;
}
}
rip-off
rip-off
It looks like you are off to a good start. Can you describe the trouble you're having?

You'll need a public static void main(String [] args) function to run the program. You'll need to make your class public too. Your function is taking a parameter, but it overwrites it. Instead, you should do the I/O outside the function, perhaps in main(). Once you can run the program this will allow you to test it for correctness.
DribbleDribble
DribbleDribble
Thank you for the quick reply!
But just a couple seconds ago I got it to work, I rewrote it and this is now what I have:

import java.util.*;
import javax.swing.*;
import java.math.*;
import java.io.Console;

public class prime
{
public static void main (String[] args)
{
int n, divisor;

Scanner scanner = new Scanner(System.in);

System.out.print("What is N? ");
n = scanner.nextInt();
divisor = n-1;
while (divisor >= 2)
{
if (n % divisor==0 )
{
System.out.println("The number " + n + " is not a prime number.");
System.exit(0);
}
divisor = divisor - 1;
}
System.out.println("The number " + n + " is a prime number.");
}
}



If you think there is a better way to go about taking care of this though, please let me know. I am always open to learning better ways to take care of things.
Rene Z
Rene Z
There is something fishy going on here:
if (n < 2 || n%2 == 0) {    if (n == 2)        return true;    else        return false;}


Also, could you please use the source tags in the future? it's a lot easier to read :)

EDIT: Never mind, you posted a reply while I was typing. Give me a moment to look at your new code
DribbleDribble
DribbleDribble
I have no problem using it :)
But I dont know how, lol.
rip-off
rip-off
Your second solution should work, but see if you can incorporate the idea in your first solution too. One tip is to always initialise your variables. You don't need to declare them at the top, declare them when they are ready to be given a value. Also, it is idiomatic to use a for() loop when you have a simple loop, rather than a while loop.

Having a separate isPrime() method is a good idea, it separates I/O from the computation.

Include [source][/source] tags around your code to get the pretty box. If you see interesting effect in someone's post, you can click "edit" on their post to see the markup they used. You won't be able to save any changes though!
dmatter
dmatter
Your first solution included the idea of checking up to sqrt(n), this radically cuts down the number of checks you need to make but your second solution misses out on this.
rip-off
rip-off
I hope you are not finding sample code online, are you writing this yourself? I wouldn't ask but your code is very different both times.
Rene Z
Rene Z
Source tag is simply the word 'source' between square brackets, and the end of source is '/source' between square brackets.

For the sake of clean code, take another look at rip-off's advice. You don't need to put all your code in main(), the isPrime(int n) should still be in a separate method:

public static void main (String[] args) {    Scanner scanner = new Scanner(System.in);    System.out.print("What is N? ");    int n = scanner.nextInt();    if(isPrime(n)){        System.out.printLine(n + " is a prime number");    } else {        System.out.printLine(n + " is not a prime number");    }}public static boolean isPrime(int n){    // Do your isPrime calculation here}


There are a few good 'isPrime' algorithms, but it's best to come up with a simple one yourself for now. I guess this is for a school assignment?
DribbleDribble
DribbleDribble
The first code I did find online but made sure I understood and edited it to what I needed. But obviously I didnt fully understand what I was doing, so I used my original code :).
DribbleDribble
DribbleDribble
Ok, so with this code:

      import java.util.*;   import java.util.*;   import javax.swing.*;   import java.math.*;   import java.io.Console;   public class prime   {      public static void main (String[] args)      {         int n, divisor;               Scanner scanner = new Scanner(System.in);               System.out.print("What is N? ");         n = scanner.nextInt();         divisor = n-1;         while (divisor >= 2)         {            if (n % divisor==0 )            {               System.out.println("The number " + n + " is not a prime number.");               System.exit(0);            }            divisor = divisor - 1;         }         System.out.println("The number " + n + " is a prime number.");      }   }



Im currently having two problems:

first off, its telling me that 0 and -1 and so on are prime numbers (along with positive 1).

Second problem, I need to loop this program, but when I do it gives me a whole slue of new problems.

Now, I had fixed first problem, but that then made 2 = not a prime, and all the others blank replies.

Any help would be GREAT!!
rip-off
rip-off
Hint: separating the logic into a helper isPrime() method will make both tasks easier. Here is your current code split like this:
   import java.util.*;   import java.util.*;   import javax.swing.*;   import java.math.*;   import java.io.Console;   public class prime   {      public static boolean isPrime(int n)      {         // TODO: handle values <= 2         int divisor = n-1;         while (divisor >= 2)         {            if (n % divisor==0 )            {               return false;            }            divisor = divisor - 1;         }         return true;      }      public static void main (String[] args)      {         Scanner scanner = new Scanner(System.in);               // TODO: put this into a loop         System.out.print("What is N? ");         int n = scanner.nextInt();         if(isPrime(n))         {            System.out.println("The number " + n + " is a prime number.");         }         else         {             System.out.println("The number " + n + " is not a prime number.");         }      }   }

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.