Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prime test, 2-digit numbers

Tags:

java

loops

primes

I want to print all prime numbers that are 2-digits long. Here is my code:

    for(int input = 11; input <= 99; input += 2){
        for(int x = 2; x < (int)Math.sqrt(input) + 1; x++){
            if(input%x != 0){
                System.out.println(input);
                break;
            }else{
                break;
            }
        }
    }

The problem is that it prints numbers like 35 or 49 which are not prime numbers.

like image 662
UpCat Avatar asked Nov 27 '22 12:11

UpCat


1 Answers

Your test for primeness is incorrect. You stop testing a number (input) as soon as you find a divisor which the input is not divisible by.

That's not the definition of prime - you need to test that the input number is not divisible by any divisors less than it - in other words you need to test all values of x before you can declare a number as prime.

You can break out of the loop that checks input % x != 0 when an input is divisible by x, but not when it is not divisible - you need to keep on checking when this condition is true!

like image 180
matt b Avatar answered Dec 09 '22 15:12

matt b