/*
This program should check if the given integer number is prime.
Reminder, an integer number greater than 1 is prime if
it divisible only by itself and by 1.
In other words a prime number divided by any other natural number
(besides 1 and itself) will have a non-zero remainder.
Your task:
Write a method called checkPrime(n) that will take
an integer greater than 1 as an input, and return true
if that integer is prime; otherwise, it should return false.
Your main() would prompt the user to enter an integer
greater than 1 and then call checkPrime() on that number.
The main() would then print a statement whether the
number was prime or not.
For example, the program output can look like this:
Please enter an integer greater than 1: 2473 <--(user input)
2473 is a PRIME!
or like this:
Please enter an integer greater than 1: 6981
6981 is a NOT a prime!
*/
import java.util.Scanner;
public class CheckPrimes {
//Returns true if n is prime
public static boolean checkPrime(int n){
/*
The strategy is pretty simple:
In a loop, try dividing number n
by every integer i starting from 2
and finishing with n/2
If a remainder from that division
is 0, that means that n is divisible by i
and n is not a prime (return false then).
If none of the divisions give you remainder 0,
then n is prime and you should return true.
*/
return true;
}
public static void main(String[] args) {
//No need to change the main()
Scanner scan = new Scanner(System.in);
System.out.print("Please enter an integer greater than 1: ");
int num = scan.nextInt();
System.out.println();
if (checkPrime(num))
System.out.println(num + " is a PRIME!");
else
System.out.println(num + " is NOT a prime!");
}
}
Program:
import java.util.Scanner;
public class CheckPrimes {
public static boolean checkPrime(int n) {
for(int i = 2; i <= n/2; ++i)
{
// condition for to check for nonprime number
if(n % i == 0)
{
return false;
}
}
return true;
}
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.print("Please enter an integer greater than 1: ");
int num = scan.nextInt(); // Taking input from user
System.out.println();
// Calling function and printing output
if (checkPrime(num))
System.out.println(num + " is a PRIME!");
else
System.out.println(num + " is NOT a prime!");
}
}
Output:
Get Answers For Free
Most questions answered within 1 hours.