Question:
How to use the square root to help determine if a number is prime?
Code:
import java.util.*; public class CheckPrime { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a number: "); Double number = input.nextDouble(); boolean prime = true; int sqrt = (int) Math.sqrt(number) + 1; for (int i = 2; i < sqrt; i++) { if (number%i == 0) { prime=false; break; } } if (prime == false) { System.out.println("The number that you entered is not prime"); } else { System.out.println("The number that you entered is prime"); } } }
Output:
$ java CheckPrime Enter a number: 22 The number that you entered is not prime $ java CheckPrime Enter a number: 101 The number that you entered is prime