Prime Number Test always returns true [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
So I just started some java and I'm trying to get the user to enter a number and test whether it is prime or not. This is the loop I have for the program.
do{
for(testNumber = 2; testNumber < numb; testNumber++){
if(numb % testNumber == 0){
test = false;
}else{
test = true;
}
}
if(test = true){
System.out.println("The number is prime.");
}else{
System.out.println("The number is not prime.");
}
System.out.println("Enter a number. Enter 0 to exit.");
numb = number.nextInt();
}while(numb != 0);
Every number that is entered becomes out to be true! To me the logic seems to be correct.

if(test = true){
should be
if(test == true){
The first one being an "assignment" operator and the second one being a logical (equality test) operator. Read more on the official documentation.
Note
I am not commenting on other parts of your code as a learning exercise for you. Your code can be optimized and improved! You're on the right track. Keep it up!

First, your are using the assignment operator = to compare test to true, which results in test always being true. It's already a boolean, just use it without the extraneous comparison:
if(test){
Second, you are overwriting the value of test in each for loop iteration. Initialize it to true, and only set it to false if you find a factor.
test = true;
for(testNumber = 2; testNumber < numb; testNumber++){
if(numb % testNumber == 0){
test = false;
}
}
Additionally, you don't need to test testNumbers past the square root of the number numb.
int limit = (int) Math.sqrt(numb);
for(testNumber = 2; testNumber <= limit; testNumber++){

You have two problems. First, think about your loop logic: You're actively setting the test variable on every pass through the loop. Since the loop ends at numb - 1, it's nearly always going to set test to true on the last pass. Instead, set test to true before the loop and only set it to false if you find a factor: That will leave it false as soon as you detect it's not prime. (Putting that loop inside a separate method so you can return immediately would be even better.)
isPrime = true;
for(int factor = 2; factor < numb; factor++) { // see below for advice on condition
if(numb % factor == 0)
isPrime = false;
}
Second, you're setting test in your if statement. You must use == to check for equality, and in Java, it's more idiomatic to just use if(test).
As a matter of style, a variable named test is not very descriptive. I suggest the isPrime name I used above.
Finally, you only need to check up to the square root of testNumber, but don't use a floating-point operation and then truncate the result, or you might miss an exact square-root factor.

You should break if you found it and if condition == true
do{
for(testNumber = 2; testNumber < numb; testNumber++){
if(numb % testNumber == 0){
test = false;
break;
}else{
test = true;
}
}
if(test == true){
System.out.println("The number is prime.");
}else{
System.out.println("The number is not prime.");
}
System.out.println("Enter a number. Enter 0 to exit.");
numb = number.nextInt();
}while(numb != 0);

Related

there is some sort of error in the syntax of the program "to determine whether the number is prime or not" in JAVA [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Even if I input the number "4", it shows that the number is prime. Please help to find error in the syntax. I have written below the program I coded :
int n = sc.nextInt();
boolean isPrime = true;
for (int i = 2; i < n; i = i + 1)
{if (n % i == 0) {
isPrime = false;
break;}
}
if (isPrime = true)
System.out.println("the number is prime");
else if (isPrime = false)
System.out.println("the number is not prime");
Boolean comparison needs to be done with double equals ==. The way you have it currently, you are setting isPrime to be true in that check. Try this:
if (isPrime == true)
Your program is not complete. You have written assignment statement instead of boolean expression in if statement. '=' sign is for assignment, As 'isPrime' is a boolean variable you can write isPrime in if expression
if(isPrime)
{
System.out.println("the number is prime");
}
else
{
System.out.println("the number is not prime");
}
Use Equality operator == instead of assignment operator = for checking the value of isPrime.
Your code should be:
boolean isPrime = true;
for (int i = 2; i < n; i = i + 1)
{if (n % i == 0) {
isPrime = false;
break;}
}
if (isPrime == true)
System.out.println("the number is prime");
else
System.out.println("the number is not prime");
Also,since if() method's return type is boolean, you can directly check with using ```==````
boolean isPrime = true;
for (int i = 2; i < n; i = i + 1)
{if (n % i == 0) {
isPrime = false;
break;}
}
if (isPrime)
System.out.println("the number is prime");
else
System.out.println("the number is not prime");

Count Even Digits in an Integer in Java [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am trying to write a method in Java that will return true if an integer only consists of even digits.
For example when the input integer is 2468, the method will return true.
Another example, if the input integer is -68, the method will return true. If the integer consisted of 24638, the method should return false.
I also am trying to use only integers. I do not want to use ToString() to take the length of the integer as my condition in my loop and I also do not want to use an array.
I have searched the forums but most replies seem to use ToString() or arrays of which I’m avoiding.
My code is below:
int countEven = 0;
int countOdd = 0;
if (n == 0)
countEven++;
while (n != 0) {
int lastdigit = n % 10;
if (lastdigit == 0 || lastdigit % 2 == 0)
countEven++;
else
countOdd++;
n = n /10;
}
if (countEven >= 0); return true;
You are not checking the condition for countodd. Lets say number is 235. Your counteven will be 1 and countodd will be 2. Then your last if condition will return true no matter what. Instead try this,
while(n != 0){
int lastdigit = n % 10;
if(lastdigit % 2 == 1)
return false;
n = n /10;
}
return true;
The problem is that your last if statement is not correct.
Try this:
if (countOdd > 0)
return false;
else
return true;

Method to search for prime numbers

I need to build a method that calculates prime numbers.
I'm testing it and it's giving me the wrong answers and I don't know how to solve it! For example, it returns true to 98262679 instead of false. Where is my mistake?
public static boolean itsPrime(int nbTest){ // Tests for prime numbers method
boolean prime = false;
if (nbTest <= 1){
return false;
} else if (nbTest == 2){ // Two is prime
return true;
} else if ((nbTest != 2) && (nbTest % 2 == 0)){ // Evens except number 2
return false; // are not prime
} else if (nbTest % 2 != 0){ // For all remaining odds
for(int i = 3; i <= Math.sqrt(nbTest); i = i+2){
if (nbTest % i == 0){
prime = false;
} else {
prime = true;
}
}
}
return prime;
}
I'm learning Java and my professor asked us to construct the method itsPrime was based on this:
For the first subtask, write a function `itsPrime` that takes an `int`
as argument and returns a `boolean`, `true` if the argument integer is prime
and `false` otherwise.
To test whether an integer x is prime, one can proceed as follows:
all integers less than or equal to 1 are not prime;
2 is prime;
all other even integers are not prime;
for all remaining integers (obviously odd), search for a divisor:
loop from 3 to the square root of the integer x (The square root of x can
be computed as ‘‘Math.sqrt(x)'' in Java.); if the remainder of the integer
division of x by the loop index is zero, then x is not prime;
if all remainders were non-zero at the end of the loop, then x is prime;
I know the answer is there somewhere in all the answers above, but I think that each require an explanation.
Here's a summary of all the enhancements you could make to your code:
1) Don't declare a boolean to return, since you are already returning true or false throughout your code. Remove this line from your code (call it [1]):
boolean prime = false;
You'll see why after you've fixed the rest of your function. Comment it out if desired, for now.
2) In your second else if, let's call it [2], you have:
else if ((nbTest != 2) && (nbTest % 2 == 0)){
return false;
}
You already checked if nbTest is 2 in your first else if, so you don't need to check if it's not 2 again. If it entered the first if else, your function will return true. When a function returns, it is done. It returns the value to the caller and the rest of the code is not executed.
Thus, you may replace that second if else, [2], with:
else if (nbTest % 2 == 0) { // all other even integers are not prime
return false;
}
3) If you enter third else if, this means that the rest of the code above already executed, and it either returned, or the program continued.
You may replace that third else if (nbTest % 2 != 0){ for:
else {
4) This is the one error that you really have to make your function return the wrong answer (call this snippet [4]):
if (nbTest % i == 0){
prime = false;
If you find that the number you are testing is divisible (i.e. the remainder is zero), you are done. You definitely know that it is not prime.
You may replace this code, [4], with:
if(nbTest % counter == 0) {
return false;
}
Thus, returning false. It is not a number. And the function does not keep executing. Your error was continuing execution after the function finds out that your input is not prime.
Finally, you may leave your return true at the end of the function body. If the function never returned from the previous tests, or from the loop, it has to be a prime number. Remember that first line I told you to remove? The boolean declaration? Since you never return a value from a variable, you just return true or false, you don't need that [1] line.
As an extra, a good read on finding prime numbers, which you might want to share with your professor:
https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
You should stop once you here:
if (nbTest % i == 0){
return false;
}
Delete the prime variable (it is an unnecessary step, see below).
Change the for loop:
for(int i = 3; i <= Math.sqrt(nbTest); i = i+2){
if (nbTest % i == 0){
prime = false;
} else {
prime = true;
}
}
To this:
for(int i = 3; i <= Math.sqrt(nbTest); i = i+2)
if (nbTest % i == 0)
return false;
This simply breaks out of the function early if it isn't prime (if a factor has been found).
You shouldn't keep testing for primality once prime has been set to false for a number.
Replace:
if (nbTest % i == 0){
prime = false;
with:
if (nbTest % i == 0){
return false;
And the last test is useless, you can just keep a basic else:
else if (nbTest % 2 != 0){ => else {
Your for loop is not correct.
A prime number is a number which is divisible by 1 and itself only. So, if a number A is divisible by any other number except 1 and itself, then A is a nonprime.
Just replace your for loop with the one below
for(int i = 3; i <= Math.sqrt(nbTest); i = i+2) {
if (nbTest % i == 0)
return false;
}
Once it is found that nbTest is divisible by some number, there is not point in continuing the loop. Return `nbTest is nonprime, then and there.

what this method does - interview [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
The following is an interview question... how can you start solve this kind of a question ? is there a general algorithm for such a questions ?
The question is to explain what this method does. I know what she gives for some inputs I tried (and it's OK), but I really don't know how to start solve this kind of a questions...
public boolean what (int num)
{
boolean ans = true;
for (int x = 2; (x*x <= num) && ans; x=x+1)
{
if ((num % x) == 0)
ans = false;
}
return ans;
}
thx !
let num = 10
public boolean what (int num)
{
boolean ans = true;
for (int x = 2; (x*x <= num) && ans; x=x+1)
{ //^ multiply x with x will give (4,9).. When x = 4, than (16<= num) = false
if ((num % x) == 0) // divide 10 by (2,3) if reminder is zero that means 10 is not prime
ans = false; // set ans to false so that for loop can be terminated or just break;
}
return ans;
}
Reverse engeering process you can follow, provide the some sample input and get the output by which you can determine the result.
Choose your input sensibly so that it would easy to solve the problem.
In present case -
Input : 1 return : true
Input : 2 return : true
Input : 3 return : true
Input : 4 return : false
Input : 5 return : true
...
Input : 9 return : false //aha...it seems to be prime number
...
Input : 111 return : false
So in this case its prime number logic.
You can find it running the method with several random inputs,
and try to find the relation between INPUT you gave and OUTPUT that appeared.
Before getting to conclusion just check it Known Output first and then declare your answer.
It checks if the num is a prime.
To find out what a method does read the code and try to understand what it is doing. You may also try some inputs. For good code the names of variables and methods also help a lot (which is not the case here).
However, if the method implements an algorithm you do not know and you do not know the context of the problem that is being solved you probably never find out what it does.
In the above program initially the number is assumed to be not prime. If any number greater than 2 and less than or equal to the square root of the number divide the given number then the number is not prime.
The method returns true if the number is not prime and returns false if the number is prime.
Purpose of method : to find out prime numbers.
This method gives an output of booleaan ans = 'true' , if input number is prime number.
Else it gives a return value of false.
It follows the simplest logic to find out if a number is prime or not..
for example if a number is 11 ,
Step 1 - we multiply it with a num till (num*num) is smaller than 11. {no need to test beyond value bigger then num*num, as all possible cases are tested }.
Step 2 - check if remainder of dividing 11/2 is zero or not , if remainder is not 0 then 11 is not prime.if it divides we go back to step 1
So the loop will be ..
Step 1 num = 11 , x = 2
Step 2 11%2 != 0 so goto step 1 , num undivisible
Step 1 num =11 , x = 3
Step2 11%3 != 0
Step 1 num = 11 , x = 4 but x*x = 16 and 16> 11 so no more looping and 11 is prime as it wasn't divisible with any number till x=3.
another example can be 38..
step 1 num 38 , x=2
step 2 38%2 ==0 , so remainder = zero and ans = false thus no more looping through and '38' is not prime.
a more advanced approach to finding a number if its prime or not could be to test its divisibility only against prime numbers. which is actually more efficient in case we have quite bigger numbers as input.
public boolean what (int num) // number to be tested is passed
{
boolean ans = true; // default value
for (int x = 2; (x*x <= num) && ans; x=x+1) //looping till num is found divisibl
{
if ((num % x) == 0)
ans = false; // ans is false in case num is not prime
}
return ans; // num is prime
}
Hope the explanation helps.. message me in case of any doubt or help.

Use Modulus Operator to Get Prime Numbers [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How would you modify the below to print out all prime numbers from 1-100? The below has an issue with the number 2 coming back as not prime. The if(i%number == 0) condition is met for the number 2 as 2%2 is returned as 0.
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
for(int i=1; i<=100; i++){
if(isPrime(i)){
System.out.println(i + " is a prime number");
}else{
System.out.println(i + " is not a prime number");
}
}
}
public static boolean isPrime(int number){
for(int i=2; i<=number; i++){
if(i%number == 0){
return false;
}else{
return true;
}
}
return false;
}
}
i<=number
You shouldn't be checking whether the number is divisible by itself.
You also have another problem:
}else{
return true;
}
You're returning true as soon as you find a single non-divisible number, even if it does have factors later.
Here is an algorithm for determining whether or not a number is prime.
Is the number less than 2? If so, return false.
Is the number 2 or 3? If so, return true.
Is the number 4? If so, return false.
Take the square root of the number, rounded up to the next integer. This is optional for small prime numbers, but speeds up the determination for larger numbers.
Loop from 5 to the square root of the number (or the number), incrementing by 2.
Divide the loop number by the prime numbers determined so far.
If the modulus of the division is zero, return false.
If the loop is completed, return true.
You've got a couple issues here. Firstly, when checking whether or not a number is prime, never check every number up to the actual number being checked for primality. A check of all primes up to the square root of the number will always be sufficient.
To fix that error look at your for loop condition and edit it accordingly:
for(int i=2; i<=number; i++)
Secondly, when a function returns it stops. Currently with your if/else statement:
if (i%number == 0) {
return false;
} else {
return true;
}
If this condition goes to the else statement even once it will return true, you want to make sure you only actually return true when you've checked all of the numbers you intend to.
Additionally I don't think you've carefully considered what you base case is. What you are saying with your last line is that if everything previously slipped through the cracks then it should assume the number isn't prime. Think about it and I'm sure you'll be able to figure it out.
This will work. 2 is a special case when testing for primes. If you start to search a larger and larger...you might want to look at the sieve of eratosphenes.
Every prime number is a multiple of another number. Take 3 for example. Using the sieve, if you find 3 to be prime it will then 'ignore' all multiples of 3 thus reducing the amount of time taken to find consequent primes. It speeds things up...ALOT :)
public class JavaApplication47 {
public static void main(String[] args) {
for(int i=1; i<=100; i++){
if(isPrime(i)){
System.out.println(i + " is a prime number");
}else{
// System.out.println(i + " is not a prime number");
}
}
}
public static boolean isPrime(int n) {
for(int i=2; 2*i<n; i++) {
if(n%i==0)
return false;
}
return true;
}
}
SIEVE EXAMPLE - NOT IMPLEMENTED - Can be used for reference and understanding.
static boolean [] allPrimes = new boolean[10000];
public static void fillTheSieve(){
Arrays.fill(allPrimes, true);
allPrimes[0] = allPrimes[1] = false; //1 and 0 are false. winning
for (int i = 2; i < allPrimes.length; i++) {
//check if prime, if so getmultiples and declae false
if(allPrimes[i]){
for (int j = 2; i*j<allPrimes.length; j++) {
allPrimes[i*j] = false;
}
}
}
}
The definition of a prime number specifically states that one cannot be a prime number.
That means that isPrime(1) should return false. Which your implementation does.
But isPrime(2) should return true. Which your implementation does not. It does not because (2 % 2 == 0) and you are checking all numbers from 2 to N, not from 2 to N-1. The last number, N, will always yield a zero remainder (N % N == 0)
Just a few things to think about when dealing with Primes. You can have a special case for 2 at the start (i.e. something like if(number == 2)...).
In addition to your error in checking all the way to i<=number consider only how far you need to go in order to be certain it is not prime, hints have already been given with i*i or Math.sqrt
Another thing in the increment i++ think about what that entails, I realize this is only for the first 100 primes but you should always be thinking about performance. Do you really have to check all numbers (2,3,4,5,6...) (hint: if you have checked if its divisible by 2 then you dont need to check for 4,6,8 etc..)
Finally with your return statements, consider using a boolean flag that you set to false/true only when you are positive the number is a prime or is not. And you only need to use 1 return statement.
Hope that helps.
Please try this
public static boolean isPrime(int number) {
for(int i = 2; i * i <= number; i++) {
if (i % number == 0) {
return false;
} else {
return true;
}
}
return true;
}

Categories