In: Computer Science
A prime number is an integer greater than 1 that is evenly divisible by only 1 and itself. For example, 2, 3, 5, and 7 are prime numbers, but 4, 6, 8, and 9 are not. Create a PrimeNumber application that prompts the user for a number and then displays a message indicating whether the number is prime or not. Hint: The % operator can be used to determine if one number is evenly divisible by another.
b) Modify the application to prompt the user for two numbers and then display the prime numbers between those numbers.
( Java programming )
a)Java code:
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner input=new Scanner(System.in);
//asking for a number
System.out.print("Enter a number: ");
//accepting it
int num=input.nextInt();
//initializing flag as 0
int flag=0;
//looping from 2 to number
for(int i=2;i<num;i++)
//checking if the number is divisible by any other
number
if(num%i==0){
//ssetting flag as 1
flag=1;
//printing Not prime
System.out.println("Not prime");
//exiting out of loop
break;
}
//checking if flag is 0
if(flag==0)
//printing Prime
System.out.println("Prime");
}
}
Screenshot:
Input and Output:
b)Java code:
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner input=new Scanner(System.in);
//asking for a number
System.out.print("Enter two numbers: ");
//accepting first number
int num1=input.nextInt();
//accepting second number
int num2=input.nextInt();
//initializing flag as 0
int flag;
//looping from num1 to num2
for(int num=num1;num<=num2;num++){
//setting flag as 0
flag=0;
//looping from 2 to number
for(int i=2;i<num;i++)
//checking if the number is divisible by any other
number
if(num%i==0){
//setting flag as 1
flag=1;
//breaking out of loop
break;
}
//checking if flag is 0
if(flag==0)
//printing Prime number
System.out.println(num);
}
}
}
Screenshot:
Input and Output: