In: Computer Science
A prime number is a number that is only evenly
divisible by itself and 1. For example, the number 5 is prime
because it can only be evenly divided by 1 and 5. The number 6,
however, is not prime because it can be divided evenly by 1, 2, 3,
and 6.
Design a Boolean function called isPrime, that accepts
an integer as an argument and returns True if the argument is a
prime number, or False otherwise. Use the function in a program
that prompts the user to enter a number and then displays a message
indicating whether the number is prime. The following modules
should be written:
getNumber, that accepts a Ref to an integer,
prompts the user to enter a number, and accepts that
input
isPrime, that accepts an integer as an argument
and returns True if the argument is a prime number, or False
otherwise
showPrime, that accepts an integer as an
argument , calls isPrime, and displays a message indicating whether
the number is prime
The main module, that will call getNumber and
showPrime
Solution:
Program implementation:
import java.util.*; // import statement for Scanner class.
public class prime{
// getNumber prompts for input.
static int getNumber(int n){
System.out.print("Enter a number: ");
Scanner sc=new Scanner(System.in);//creates an object of scanner
class.
n=sc.nextInt(); // takes input.
System.out.println(n); // prints input.
return n; // returns the n value.
}
// isPrime() function checks whether n value is prime or not.
static boolean isPrime(int n){
if(n==0 || n==1){
return false; // if n ivalue is 0 or 1 returns false.
}
for(int i=2;i<=n/2;i++){
if(n%i==0) // if n has more than 2 factors returns false.
return false;
}
return true; // if n has only two factors.
}
static void showPrime(int n){
if(isPrime(n)){ // if isPrime() returns true.
System.out.println(n+" is a prime number.");
}
else{ // if isPrime() returns false.
System.out.println(n+" is not a prime number.");
}
}
public static void main(String []args){
int n=0; // variable to take input.
n=getNumber(n); // function call to getNumber().
showPrime(n); // function call to showPrime().
}
}
Program screenshot:
Program input and output screenshot: