Hi,

I have to write a program that tests if a number entered is prime or not.

I have finished all the code to display input prompts and output message

Example: " Enter a number: " - " x is a prime number" - " x is not a prime number" etc

Does anyone know how to write the code to test if a number is prime or not?

I think I would have to divide the input number and check if it is equal to 0. If it is equal to 0 it would not be prime.

Something like this:

division = 2;

input / division

If( division == 0)
System.out.println( result + " is not a prime number");

I'm not sure.

Appreciate any help with this.

Thank you

3
Contributors
5
Replies
6
Views
13 Years
Discussion Span
Last Post by nanosani

See if this function works :

``````public void calculatePrime(int number){
for( int i = 2; i < number i++){
if((number % i) == 0){
System.out.println("The number you entered is not a prime");
return;
}
}
System.out.println("The number you entered is prime");
}``````

See if this function works :

``````public void calculatePrime(int number){
for( int i = 2; i < number i++){
if((number % i) == 0){
System.out.println("The number you entered is not a prime");
return;
}
}
System.out.println("The number you entered is prime");
}``````

Thank you very much, I will write it in with my code tonight and see how it goes, Thank you!!!!!!!!!!!

You are a great help!!!!!!!

Your code looks like all conjusted ... I've tried to read it but you should check for the opening and closing brackets ... your if statement was not in the for loop.

``````import java.io.*;

public class PrimalityTest
{

public static void main(String[] args)throws IOException
{

// create a keyboard input stream

// variables to store input
int Input;

do
{

// prompt for user input

// test for prime number

for (int i = 2; i < Input; i++)
{
if ((Input % i) == 0)
{
System.out.println(Input + " is not a prime number"); // here is the non  working loop, it stops here when the number is not prime
return;
}

}
}
while (Input !=0);
}
}``````

The clue is in the 'return'.

Maybe you meen to do something else?

May be you could use break instead of return.... I had written the method seperately and you merged it into the main method.

``````import java.io.*;

public class PrimalityTest
{

public static void main(String[] args)throws IOException
{

// create a keyboard input stream

// variables to store input
int Input;

do
{

// prompt for user input

// test for prime number

for (int i = 2; i < Input; i++)
{
if ((Input % i) == 0)
{
System.out.println(Input + " is not a prime number"); // here is the non  working loop, it stops here when the number is not prime
break;
}

}
}
while (Input !=0);
}
}``````
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.