Home > Software engineering >  for getting the prime numbers in a range(eg: 1 to 10) and also total count of the output
for getting the prime numbers in a range(eg: 1 to 10) and also total count of the output

Time:01-19

I am using the below code and it's giving me the option to enter the final value but I need to give input of two values and also the total count of prime numbers between that range.

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Please enter two positive integers: ");
    int input = scanner.nextInt();
    List<Integer> primes = new ArrayList<>();

    // loop through the numbers one by one
    for (int i = 2; i < input; i  ) {
        boolean isPrimeNumber = true;

        // check to see if the number is prime
        for (int j = 2; j < i; j  ) {
            if (i % j == 0) {
                isPrimeNumber = false;
                break; // exit the inner for loop
            }
        }

        // print the number if prime
        if (isPrimeNumber) {
            primes.add(i);
        }
    }
    System.out.println("The number of prime is: "   primes.size());

    System.out.println(primes.toString());
}

CodePudding user response:

All you need is to ask the user for two integer numbers using Scanner two times.

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter two positive integers:");

    System.out.print("low range: ");
    int lo = scan.nextInt();

    System.out.print("high range: ");
    int hi = scan.nextInt();
    List<Integer> primes = getPrimeNumbers(lo, hi);

    System.out.println("The number of prime is: "   primes.size());
    System.out.println(primes);
}

private static List<Integer> getPrimeNumbers(int lo, int hi) {
    List<Integer> primes = new ArrayList<>();

    for (int i = lo; i <= hi; i  )
        if (isPrime(i))
            primes.add(i);

    return primes;
}

private static boolean isPrime(int val) {
    if (val == 1)
        return false;
    if (val == 2 || val == 3)
        return true;

    for (int i = 2, sqrt = (int)Math.sqrt(val); i <= sqrt; i  )
        if (val % i == 0)
            return false;

    return true;
}

CodePudding user response:

Your but fine but not exactly as you've described.

scanner.nextInt() - can produce only one int value (or causes InputMismatchException if input isn't an int).

You said 'i need to give input of two values' - to accomplish it you may have to read these values separately using nextInt() or you can read both as a line, then split the line, and parse to int separately. The first option is definitely easier.

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Please enter two positive integers: ");
    System.out.print("start = ");
    int start = scanner.nextInt();
    System.out.print("end = ");
    int end = scanner.nextInt();

    List<Integer> primes = new ArrayList<>();

    // loop through the numbers from start to end inclusive
    for (int i = start; i <= end; i  ) {
        // check if i is prime
        if (isPrime(i)) {
            primes.add(i);
        }
    }
    System.out.println("The number of prime is: "   primes.size());
    System.out.println(primes);
}

private static boolean isPrime(int i) {
    boolean isPrime = true;
    // check to see if the number is prime
    for (int j = 2; j < i / 2; j  ) {
        if (i % j == 0) {
            isPrime = false;
            break; // exit the inner for loop
        }
    }
    return isPrime;
}

Let us know, please, is that what you wanted to achieve?

And because this question is related to the prime numbers, it is worse to point out that this algorithm isn't a very effective way to deal with this task.

To improve performance instead of blindly iterating through the whole range of values, again and again, primes that are already discovered must be reused.

I don't want to overwhelm you by making a lot of changes to your code in one go. If you wish to look at the alternative approach drop me a line.

CodePudding user response:

  1. use two Scanners to get second input
  2. you can remove the list and adding elements to it and use a counter if you want only the number of prime numbers :)

So the solution would be :

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Please enter the first positive integer: ");
    int firstNumber = scanner.nextInt();
    System.out.println("Please enter the second positive integer: ");


// you should have another scanner hence an other text output to invite user
    int secondNumber = scanner.nextInt();

    List<Integer> primes = new ArrayList<>(); // we do not really need this if we want only the number of prime number and not the list but i'll use it for you anyway

    for(int i = firstNumber; i <= secondNumber; i  ) //the use the input variables
    {
        if (isPrime(i)){ // we made a function here to make things clear. it's role to tell weather a number is a prime or not
            primes.add(i); // we add prime numbers to this list as you used a  list. You can go for an easier solution just a counter   each time ;)
        }
    }

    System.out.println("The number of prime numbers in this range is: "   primes.size());

}
static boolean isPrime(int num){
    if (num <= 1)
        return false;
    for(int i = 2; i * i <= num; i  )
        // If a divisor of n exists
        if (num % i == 0)
            return false;

    return true;
}
  •  Tags:  
  • Related