8. Write a program that reads an integer from the keyboard and tells the user if the number is prime. Use a for loop to check if the number is divisible by the numbers from 2 up to the value of the input number minus 1.
import java.util.*;
public class Arithmetic {
public static void main(String[] args) {
int input;
int i;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a positive number: ");
input = keyboard.nextInt();
for (i = input - 1; i >= 2; i--) {
if ((input % i) == 0) {
System.out.println(input + " is not prime.");
break;
}
}
if (i == 1)
System.out.println(input + " is prime.");
keyboard.close();
}
}
No comments:
Post a Comment