Write it in java Ask user to give a positive number and report back if it is pri
ID: 3704946 • Letter: W
Question
Write it in java
Ask user to give a positive number and report back if it is prime.To test if a single number is prime, you need to test if any number smaller than it can be divided evenly into it. To know if an individual number X is evenly divisible by Y, the remainder from a division of X/Y is zero.We can use the modulus operator, Example:if (X % Y == 0 )then it is divisible.You may want to create a variable to keep track of how many numbers are evenly divisible into the user’s number. Use a loop to cycle through the division. Once you have this part working, put the whole thing in a larger loop that will allow the program to run continuously unless 0 is entered. Inform the user that they must enter 0 in order to end the program. Sample output: Enter a positive number to see if it is prime. Enter a 0 to end the program. >>>17 This is a prime number. Enter a positive number to see if it is prime. Enter a 0 to end the program. >>>0 Goodbye. Please do it by using simple while,if or for loops
Explanation / Answer
PrimeNumTester.java
import java.util.Scanner;
public class PrimeNumTester {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a positive number to see if it is prime. Enter a 0 to end the program. >>>");
int num = scan.nextInt();
while(num != 0){
if(isPrime(num)) {
System.out.println(num+" is a prime number");
} else {
System.out.println(num+" is not a prime number");
}
System.out.println("Enter a positive number to see if it is prime. Enter a 0 to end the program. >>>");
num = scan.nextInt();
}
}
public static boolean isPrime(int num) {
for (int f = 2; f <= num / 2; f++) {
if (num % f == 0) {
return false;
}
}
return true;
}
}
Output:
Enter a positive number to see if it is prime. Enter a 0 to end the program. >>>
17
17 is a prime number
Enter a positive number to see if it is prime. Enter a 0 to end the program. >>>
23
23 is a prime number
Enter a positive number to see if it is prime. Enter a 0 to end the program. >>>
37
37 is a prime number
Enter a positive number to see if it is prime. Enter a 0 to end the program. >>>
12
12 is not a prime number
Enter a positive number to see if it is prime. Enter a 0 to end the program. >>>
0
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.