-2

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;
    }

}
c12
  • 9,557
  • 48
  • 157
  • 253
  • You are asking this why exactly? What have you tried, what has not worked? – Micha Wiedenmann Jul 23 '13 at 17:32
  • 2
    Your for loop in isPrime is broken. It always returns within the first iteration. Also pls debug my code questions are usually not sutable for this site. – ClassicThunder Jul 23 '13 at 17:34
  • 1
    @ClassicThunder He's asking why it doesn't work as expected (thus where's the logic error). Looks like a completely legit question to me. – m0skit0 Jul 23 '13 at 17:37
  • 1
    The fact that the question is about logic does not make it OK to ask: "Please debug the following code for me" questions. – Eric Leschinski Jul 23 '13 at 17:55
  • possible duplicate of [What would be the fastest method to test for primality in Java?](http://stackoverflow.com/questions/2385909/what-would-be-the-fastest-method-to-test-for-primality-in-java) – Has QUIT--Anony-Mousse Jul 23 '13 at 18:07

7 Answers7

2
 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.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
2

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.
Gilbert Le Blanc
  • 50,182
  • 6
  • 67
  • 111
  • old thread I know, but where does this come from? Is there a source? – orionrush Jun 04 '20 at 21:58
  • I wrote this nearly seven years ago, so if there was a source, I don't remember. The square root trick is pretty common. You can also increment the for loop by two and avoid the divide by 2 tests. – Gilbert Le Blanc Jun 04 '20 at 22:13
1

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.

Slater Victoroff
  • 21,376
  • 21
  • 85
  • 144
1

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;

            }
        }

    }
}
null
  • 3,469
  • 7
  • 41
  • 90
0

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)

Edwin Buck
  • 69,361
  • 7
  • 100
  • 138
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.

chancea
  • 5,858
  • 3
  • 29
  • 39
-4

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;
}
seanxiaoxiao
  • 1,282
  • 2
  • 11
  • 23