Write a program that prints out all prime numbers up to a value entered by the u
ID: 3596249 • Letter: W
Question
Write a program that prints out all prime numbers up to a value entered by the user. Begin the program by asking the user to enter an integer. Your program should then print out all of the prime numbers up to the user's number - one per line. The following is an example of what your MIGHT see on the screen when your program runs. The exact output depends on what values that the user types in while the program runs. The user's inputted values are shown below in italics: Enter an integer (2 or above): 19 The prime numbers up to your integer are: 2 3 5 7 11 13 17 19 Here is another example program run: Enter an integer (2 or above): 1 Not a valid number. Technical Notes & Requirements: If the user enters a number below 2, your program should print a message that the number is not valid, and then stop. A number is a prime number if it is not divisible by any number except 1 and itself. For this program, in order to test a number to see if it is prime, you should try to divide the number by every value from 2 up to the number-1, to see if it divides evenly or not. For example: To see if 5 is a prime number: 5 does not divide evenly by 2 5 does not divide evenly by 3 5 does not divide evenly by 4 therefore 5 is a prime number To see if 9 is a prime number: 9 does not divide evenly by 2 9 divides evenly by 3 therefore 9 is not a prime number This program requires you to write nested loops (that is, a loop inside a loop). One loop will be used to count from 2 up to the user's number so that you can test each of these numbers to see it it is prime. For each of these numbers, x: A nested loop will check all values from 2 up to x-1 to see if x divides evenly by any of them. You will need to use a Boolean variable (also referred to as a flag variable) to help you determine whether or not to print a number to the screen.
Explanation / Answer
Java program to print primes between the specified range:
import java.util.Scanner;
class PrintPrimesInRange
{
//this method evaluates if the number is prime or not
static boolean checkPrime(int num)
{
boolean flag=true;
for(int i=2; i<=(num/2);i++)
{
if(num%i==0)
{
flag=false;
break;
}
}
return flag;
}
public static void main(String[] args)
{
int n;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the value of N: ");
n = sc.nextInt();
if (n < 2)
System.out.print("Not a valid number");
else {
for(int loop=2; loop<=n; loop++)
{
if(checkPrime(loop)==true)
System.out.println(loop+" ");
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.