'Print 1 or 0 if value is prime
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();
}
}
}
Solution 1:[1]
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!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Avinash Verma |
