Joe
Joe

Reputation: 11

Program wrongly states whether numbers are prime

I wrote this code to determine which numbers between two numbers someone types are prime and which are composite. The user types two numbers, e.g. 5 & 10, and in that case the program should output:

5 is prime 6 is not prime 7 is prime 8 is not prime 9 is not prime 10 is not prime

But it is not doing this correctly. For example, if the user enters 13 and 33, the output is that 13, 14, and 15 are prime, but all the other numbers are not. What's even more strange is that the results contradict each other. For example, if the user enters 10 and 20, the program outputs that all the numbers are not prime.

package more.basic.applications;
import java.util.Scanner;

public class MoreBasicApplications {

public static void main(String[] args) 
{       

    //program to determine how many numbers between 2 numbers inclusive are prime, and how many are composite, as well as display them

    int j = 2;
    Scanner reader = new Scanner(System.in);
    System.out.println("Please enter number 1, between 0 and 100: ");
    int number = reader.nextInt(); 

    boolean composite = false;  

    System.out.println("Please enter number 2, between 0 and 200: ");
    int number2 = reader.nextInt();

    int difference = number2 - number; 

    int[] array = new int[difference+1]; 

    for (int i = 0; i < array.length; i++) 
    {
        array[i] = number + i; 

        while (j <= Math.sqrt(array[i])) 
        {        
            if (array[i]%j == 0) {
                composite = true; 
            }
            j++; 
        }

        if (composite == true) {
            System.out.println (array[i] + " is not prime.");
        }
        else 
        {        
            System.out.println (array[i] + " is prime.");
        }
    }
}

Upvotes: 0

Views: 27

Answers (1)

Erik Brown
Erik Brown

Reputation: 26

It looks like you don't "reset" j back to 2 at the beginning of your for loop, so j keeps getting bigger and bigger.

for (int i = 0; i < array.length; i++) {
  j = 2; // reset j back to 2.
  array[i] = number + i; 

  while (j <= Math.sqrt(array[i])) { 

    if (array[i]%j == 0) {
      composite = true; 
    }
    j++; 
  }
  if (composite == true) {
    System.out.println (array[i] + " is not prime.")
  } else {
    System.out.println (array[i] + " is prime.");
  }
 }

Upvotes: 1

Related Questions