Question: I m providing starting code that you will need to use for this. We want to find out all the prime numbers between 1 and

Im providing starting code that you will need to use for this. We want to find out all the prime numbers between 1 and some user entered value.
* Algorithm explanation: we will create a boolean array that size and make all values initially true. Then we will switch all values divisible by 2 to false. Then we will repeat for 3. We will continue until we have checked them all. You need to think hard about what it means to "have checked them all". Be as efficient as you can.
NOTE: you might think that n/2 is the upper limit for which you must test to see whether a number n is prime, but you need only go as high as the square root of n. Think about it...
import java.util.Scanner;
/*// We want to find out all the prime numbers between 1 and some user entered value
* Algorithm explanation : we will create a boolean array that size and make all values
* initially true. Then we will switch all values divisible by 2 to false. Then we will
* repeat for 3. We will continue until we have checked them all. You need to think hard
* about what it means to "have checked them all". Be as efficient as you can
*/
public class Primes{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("This program will create all the prime numbers for you: ");
System.out.println("What is your maximum number?");
int max = scanner.nextInt();
scanner.close();
// create a boolean array that is one size larger than the max variable
//(ex if I want to check primes for 1-10, I want to set up a boolean array with index 0-10)
// we will ignore the zeroth location
// loop through the array that you made and make each value initally equal to true
// utilize a for loop to switch all non prime locations to false.
// I used a for loop inside of an if that was inside of my main for loop
// so starting with 2, I want to switch 4,6,8,10, etc. up to less than max
// then do the same for 3. Switch 3,6(which is already switched),9,12, up to less than max
// etc.
//see if you can optimize your algorithm.
// call your printPrime() method - see below -- to print the prime numbers
}
//write a method printPrime(int n, boolean[] nums) that passes in the max number and the
//boolean array. Have it print only the prime numbers, all on one line. See sample output/
}
SAMPLE OUTPUT:
This program will create all the prime numbers for you:
What is your maximum number?
50
Prime numbers smaller than 50:
23571113171923293137414347

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!