Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.math.*;
- import java.util.Scanner;
- public class CheckPrimeNumber {
- final static BigInteger BIG_INTEGER_TWO = new BigInteger("2");
- public static void main(String[] args)
- {
- try{
- Scanner sc= new Scanner(System.in);
- System.out.println("Enter a valid positive number: ");
- String strinput=sc.nextLine();
- BigInteger input = new BigInteger(strinput);
- BigInteger num = input.divide(BIG_INTEGER_TWO);
- sc.close();
- boolean isPrime = isPrime(input);
- if (isPrime) {
- System.out.println(input +" is a prime number.");
- } else {
- System.out.println(input+" is not a prime number.");
- }
- }
- catch(Exception e){
- System.out.println("Please enter only valid positive number: ");
- }
- finally{
- System.out.println("Thank you...!!!");
- }
- }
- protected static boolean isPrime(BigInteger input) {
- boolean isPrime = false;
- if(input.equals(0)){
- isPrime = false;
- }
- if(input.equals(1)){
- isPrime = false;
- }
- else {
- int flag = 0;
- for (BigInteger one = BigInteger.ONE; one.compareTo(input.divide(BIG_INTEGER_TWO)) < 0; one = one.add(BigInteger.ONE)) {
- // Above line is still giving the error. It cannot be converted from int to boolean.
- // I understood what you suggested, but I am not able to implement that logic.
- if (input.remainder(BIG_INTEGER_TWO).equals(BigInteger.ZERO)) {
- isPrime = false;
- flag = 1;
- break;
- }
- }
- if(flag==0) {
- isPrime = true;
- }
- }
- return isPrime;
- }
- }
Add Comment
Please, Sign In to add comment