Click here to Skip to main content
15,919,879 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I'd appreciate help on the task I am given.

A prime number is an integer greater than 1 that is only evenly divisible by 1 and itself.
Complete the isPrime() method, which takes an integer argument. This method
returns a boolean value: true if the argument is prime, and false otherwise. Perform
the required calculations in your method; DO NOT simply use a list of pre-calculated
prime numbers or an if-else chain!

This is what I have.
I don't know where I should place my print statements so that when a number is entered, it tells you whether or not it is prime.

Java
public static boolean isPrime(int n){
System.out.println("Enter a number to determine if it is prime: ");
boolean prime = true;

if (n % 2 == 0){
return false;
}
for (int i = 3; i < n; i++){
if (n % i == 0){
prime = false;
break;
}
return prime
}
Posted
Updated 16-May-13 14:09pm
v4
Comments
[no name] 16-May-13 19:43pm    
Okay.... and the problem and/or question and/or the help you need is what exactly?
Promethin 16-May-13 20:04pm    
Sorry, I posted what I have in the solution area. I don't know where I should place my print statements so that when a number is entered, it tells you whether or not it is prime.
[no name] 16-May-13 20:48pm    
How about either before you return from isPrime or right after you call isPrime?
Sergey Alexandrovich Kryukov 16-May-13 19:44pm    
Homework? Anyway, you have to solve the problem by yourself, at least show what did you try.
—SA
PIEBALDconsult 16-May-13 21:27pm    
That's up to the caller.

Seeing that makes me not want to learn Java.

P.S. Hint -- You don't need to look for factors above the square root.

1 solution

YOur

Java
System.out.println("Enter a number to determine if it is prime: ");


shouldn't be inside the function.

OUTSIDE of the function you would need to have (pseudoCode)

Java
Ask the user for a number
Get the number from the user
Call the function, passing the number entered
if (the Function Returned True)
    Tell the user it's a prime
Else
    Tell the user it's not a prime


So the function itself JUST calculates if the number is a prime. That way, if you find a better algorithm in the future (hint see PiebaldConsult's hint!), you can just rewrite that one function without messing up the rest of the program.

Good luck!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900