Answer to Question #302733 in Java | JSP | JSF for Smiles

Question #302733

Develop a Java program to compute and display all prime numbers between two numbers that the user enters(eg if the user enters 2 and 12 it displays 3,7,11 each in a new line. If the user enters the same numbera, program must keep giving an error message and prompting user to enter different numbers only. Use array to store numbers, use appropriate functions and control structures

1
Expert's answer
2022-02-25T17:39:15-0500
import java.util.Scanner;

public class Main {

    public static void primes(boolean[] primes) {
        for (int i = 2; i < primes.length; i++) {
            for (int j = i * i; j < primes.length; j += i) {
                primes[j] = true;
            }
        }
    }


    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int start;
        int end;
        while (true) {
            System.out.println("Start: ");
            start = in.nextInt();
            System.out.println("End");
            end = in.nextInt();
            if (start < end) {
                break;
            } else {
                System.out.println("start >= end");
            }
        }
        boolean[] primes = new boolean[end + 1];
        primes(primes);
        for (int i = start + 1; i < end; i++) {
            if (!primes[i]) {
                System.out.print(i + " ");
            }
        }
        System.out.println();
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS