0

write a program in java using object oriented principle to check whether a number is prime or not. If it is prime then print 1 if it is false then 0 if the given value is less then or equal to 1 then print -1. Take the values from the user?

when i give single digit values it works but when i give 2 digits value it doesn't work

import java.util.Scanner;

class Prime1 {
int n;
Prime1 (int n)
{
    this.n=n;
}
boolean isPrime()
{
    if(n==2)
    {
        System.out.println("1");
        return true;
       
    }
    else if (n%2==0)
    {
        System.out.println("0");
        return false;
    }
    for (int i = 3;i<=Math.sqrt(n);i+=2)
    {
        if(n%i==0)
        System.out.println("0");
        return false;
    }
    System.out.println("1");
    return true;

}
}


class CheckPrime
{
public static void main(String[] args) 
{
    System.out.print("Enter a number you want to check :: ");
    Scanner scan = new Scanner(System.in);
    int num1 = scan.nextInt();
    scan.close();
    Prime1 obj = new Prime1(num1);
    if(num1<=1)
    {
        System.out.print("-1");
    }        
    else
    {
        obj.isPrime();

    }
}
}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Lo9EWo1F_
  • 3
  • 1

1 Answers1

2

change the for loop to

  for (int i = 3;i<=Math.sqrt(n);i+=2)
{
    if(n%i==0)
    {
      System.out.println("0");
      return false;
     }
}

You forgot to put curly bracket after if which results in for loop running only once!