In: Computer Science
Using Java
Prime numbers. Write a program that prompts the user for an integer and then prints out all prime numbers up to that integer. For example, when the user enters 20, the program should print 2 3 5 7 11 13 17 19 Recall that a number is a prime number if it is not divisible by any number except 1 and itself. Use a class PrimeGenerator with methods nextPrime and isPrime. Supply a class PrimePrinter whose main method reads a user input, constructs a PrimeGenerator object, and prints the primes. Submit the Java file and screenshot of the output in zip file.
package october;
import java.util.Scanner;
public class PrimeGenerator {
//class variables
private int limit; //will store the limit till when
primes are to be generated
private int start = 2; // will start from 2
//constructor to initialise
public PrimeGenerator(int limit) {
this.limit = limit;
}
//method to print all the primes
public void printPrimes() {
System.out.println("The primes upto
" + limit + " are: ");
//loop will iterate until lower
limit is less than upper limit
while(start <= limit){
//this willl get
the immediate next prime.
int p =
nextPrime();
System.out.print(p + " ");
}
}
//this ,ethod will give the next prime
private int nextPrime() {
//if start > limit then exit the
program
if(start > limit){
System.exit(0);
}
//checking if start is prime or
not
if(isPrime(start) > 0) {
//inc. start for
the next iteration
start++;
return
start-1;
}
else {
//if start is
not prime
//inc. it by
1
start++;
//calulating the
next prime
return
nextPrime();
}
}
//method to check whether i is prime or not
private int isPrime(int i) {
if(i == 2) return i;
if(i == 3) return i;
for(int j = 2 ; j <=
Math.sqrt(i) ; j++){
if(i % j == 0)
return 0;
}
return i;
}
public static void main(String[] args) {
System.out.println("Enter the
number till you want prime numbers: ");
Scanner sc = new
Scanner(System.in);
int n = sc.nextInt();
PrimeGenerator pg = new
PrimeGenerator(n);
pg.printPrimes();
sc.close();
}
}
if there is anything that you do not understand or need more help then please mention it in the comments section.