Write a Java program that prints the first n prime numbers, where n is a positiv
ID: 3864131 • Letter: W
Question
Write a Java program that prints the first n prime numbers, where n is a positive integer that is given as input (from the user). For example, if the user enters 8, the program prints out the first primes as follows: The first 8 primes are: 2, 3, 5, 7, 11, 13, 17, 19. The program must print out the first n primes for every n given by the user. The program should terminate only when the user enters a number that is not positive (the sentinel value). As an example, the following is the output of a sample run of the program: Enter a positive integer: 5 The first 5 primes are 2 3, 5, 7, 11. Enter another positive integer: 3 The first 3 primes are: 2 3, 5. Enter another positive integer: 8 The first 8 primes are: 2, 3, 5, 7, 11, 13, 17, 19. Enter another positive integer: The first 15 primes are: 2 3, 5, 7, 11, 13, 17, 19, 23 29, 31, 37, 41, 43, 47. Enter another positive integer: 20 The first 20 primes are: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31 37, 41, 43 47 53, 59, 61, 67, 71. Enter another positive integer: 0 OK... Bye!Explanation / Answer
The Java Program that prints the first n Prime Numbers, where n is a Positive Integer that is given as input from the End-User:-
import java.util.*;
class Primes
{
public static void main(String[] args)
{
int i,j;
int No_of_factors;
String primes = " ";
Scanner s = new Scanner(System.in);
System.out.println("Enter a positive integer");
int n = s.nextInt();
if (n >= 1)
{
for (i = 1; i <= n; i++)
{
No_of_factors=0;
for(j =i; j>=1; j--)
{
if(i%j==0)
{
No_of_factors = No_of_factors + 1;
}
}
if (No_of_factors == 2)
{
primes = primes + i + " ";
}
}
System.out.println("First "+n+" primes are: ");
System.out.println(primes);
System.out.println("Enter another positive integer");
}
else
{
System.out.print("OK... Bye!");
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.