**** The following in JAVA**** Find Prime Numbers Given an integer, find whether
ID: 3882539 • Letter: #
Question
**** The following in JAVA****
Find Prime Numbers
Given an integer, find whether the numbers is a Prime number or not.
Write a function: int isPrime(int number) that accepts an integer number.
The isPrime function returns 1 if number is prime else 0.
Input: 11
Output: 1
EX: 11 can be divided exactly by 1 and 11. Hence it's a prime number.
Assume that, number is integer within the range [ –2,147,483,64 to 2,147,483,64 ].
****USE THE FOLLOWING DRIVER ***
* Do not modify the driver, just make a new class and method that function with the provided driver
public class DriverMain {
public static void main(String args[]){
Scanner s = new Scanner(System.in);
int n = s.nextInt();
HW2_P1 hw2p1 = new HW2_P1();
System.out.print(hw2p1.isPrime(n));
}
}
Explanation / Answer
JAVA PROGRAM :
import java.util.Scanner;
class HW2_P1{
public int isPrime(int x){
//if x is -1,0 or 1, return 0
if(x<=1&&x>=-1){
return 0;
}
//2 is prime
if(x==2||x==-2){
return 1;
}
//Even number is not prime
if(x%2==0){
return 0;
}
int e = (int)Math.ceil(Math.sqrt(x));
//Check with all the odd numbers till sqrt x
for(int i=3;i<=e;i+=2){
if(x%i==0){
return 0;
}
}
return 1;
}
}
class DriverMain {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
HW2_P1 hw2p1 = new HW2_P1();
System.out.println(hw2p1.isPrime(n));
}
}
OUTPUT :
Input : 52:
Output : 0
Input : 113
Output : 1
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.