Prime numbers. Write a program that prompts the user for an integer and then pri
ID: 3641213 • Letter: P
Question
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.
Complete the following two classes for this assignment.
import java.util.Scanner;
/**
This class prints prime numbers.
*/
public class PrimePrinter
{
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter upper limit: ");
int limit = in.nextInt();
PrimeGenerator pg = new PrimeGenerator();
}
}
/**
This class generates all prime numbers.
*/
public class PrimeGenerator
{
private int current;
public PrimeGenerator()
{
current = 1;
}
/**
Calculates the next prime number.
@return the next prime number
*/
public int nextPrime()
{
Explanation / Answer
package util;
import java.util.Scanner;
public class Prime {
public static void main(String[] args)
{
int n,p;
Scanner s=new Scanner(System.in);
System.out.println("Enter upto which number prime numbers are needed");
n=s.nextInt();
for(int i=2;i<n;i++)
{
p=0;
for(int j=2;j<i;j++)
{
if(i%j==0)
p=1;
}
if(p==0)
System.out.println(i);
}
}
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.