Reputation: 550
Given three numbers as input, return true if at least one of them is a prime number. For solving this problem, define a function that checks whether a number is a prime or not and use that function
MyApproach:
I made a function that checks first whether the num is prime or not(CHECK PRIME).After checking the 3 numbers,if in that function any of the number is prime it should return true otherwise false.
But I am getting wrong Ans for the test case
Below is my Code:
public boolean anyonePrime(int num1, int num2, int num3)
{
boolean b1=checkPrime(num1);
boolean b2=checkPrime(num2);
boolean b3=checkPrime(num3);
if((b1==true) ||(b2==true) ||(b3==true)) //@Edit
return true;
else
return false;
}
public boolean checkPrime(int num)
{
boolean b0=true;
if(num==1)
return false; //@Edit
else
{
for(int i=2; i<=num/2; i++)
{
if(num % i==0)
{
return false; //@Edit
}
}
return true;
}
if(b0==true)
return true;
else
return false;
//write your code here
}
}
@ Edit passes all test cases For the Input
Parameters ActualOutput Expected Output
'169' '361' '529' true false
Upvotes: 2
Views: 1428
Reputation: 7057
The main issue is that b0=true
always. But..
Upvotes: 3
Reputation: 610
Try this:
public boolean anyonePrime(int num1, int num2, int num3)
{
return (checkPrime(num1) || checkPrime(num2) || checkPrime(num3))
}
public boolean checkPrime(int num)
{
boolean b0=true;
if(num==1)
b0=false;
else
{
for(int i=2; i<=num/2; i++)
{
if(num % i == 0)
{
b0=false;
}
}
}
if(b0==true)
return true;
else
return false;
//write your code here
}
}
I just removed the 'b0 = true line' and tidied up some code
Upvotes: 2
Reputation: 1849
You appear to have a typo in your code. You set b0=true;
before checking if(b0==true);
, so it will always return true
. The simple thing to do would simply be to return false
as soon as any check finds it is not prime, rather than setting b0
to false
and then continuing to do more work.
Upvotes: 3