IN JAVA: O centralLinkl Central Mic Take Test: Lab 146-Met x/ https://black oard
ID: 3711676 • Letter: I
Question
IN JAVA:
O centralLinkl Central Mic Take Test: Lab 146-Met x/ https://black oardcmich.edu webapps assessment take launch sp?course assessment id= 22/1 19 18 course id= 14088/ 1&content; id-5 × ? Secure 69513 18 step-null Apps Home| Central Mich Zy Central Mithigan Uri Faball 201 Horme Chegg.com QUESTION 2 A prime number is a natural number that is greater than 1 and has no positive divisors other than 1 and itself. Write a program named IsPrime which can determine if an integer number is a prime or not. More specifically: . In main method, construct a loop to prompt user for an integer and call the isPrime method to check if the number is a prime or not The isPrime method should take an integer as input, and return a boolean (true if the number is a prime, false if not) Attach File Browse My Computer Click Save and Submit to save and submit. Click Save All Answers to save all answers. Show all TR schedule rewrit-.xsx ^ 13A-method-sol docx ^ O Type here to search 10:54 AM 4/19/2018 9Explanation / Answer
The java code is as follows :
import java.util.*;
import java.lang.*;
import java.io.*;
class Prime
{
public static boolean isPrime(int number)
{
if(number == 1) // special case for 1
{
return false; // not a prime
}
int number_of_divisors = 0; // initializing number of divisors as zero
for(int i = 1 ; i <= number; i++) // running a loop from 1 to the number itself
{
if(number % i == 0) // checking to see if the number is divisible with any i
{
number_of_divisors++; // incrementing number of divisors if divisible
}
}
if(number_of_divisors > 2) // if number of divisors is greater than 2 then not a prime
{
return false;
}
else // else a prime
{
return true;
}
}
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in); // defining an object of the Scanner class
System.out.println("Enter a number"); // prompting for an input
int input = sc.nextInt(); // taking input
boolean output = isPrime(input); // calling the isPrime function
if(output == true) // to check if its Prime
{
System.out.println(input+" is a Prime number"); // printing the output
}
else
{
System.out.println(input+" is not a Prime number");
}
}
}
Output :
Enter a number
2
2 is a Prime number
Enter a number
4
4 is not a Prime number