In: Computer Science
Ask user to input the integer number test the number whether it is a prime number or not Then, print “true” or “false” depending on whether the number is prime or isn’t. Hint: number is prime when is has exactly 2 factors: one and itself. By this definition, number 1 is a special case and is NOT a prime. Use idea of user input, cumulative sum, and loop to solve this problem. You can assume user inputs positive number.
The following is the code for the above question.
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int i,num;
boolean isPrime=true; //a boolean type to check if the num is prime or not
System.out.print("Enter any number to check whether it is prime or not: ");
num=in.nextInt(); //input number
System.out.println();
if(num==1) //if num is 1, then it is not prime (you can also add condition if num<0 to get rid of negative numbers)
{
isPrime=false; //set isPrime to false =>not prime
}
else
{
for(i=2;i<num;i++) //loop check from 2 to num. You can also use i<=n/2 for reducing time complexity
{
if(num%i==0) //if it has any factor
{
isPrime=false; //set isPrime to false and break the loop
break;
}
}
}
if(isPrime) //check if isPrime
{
System.out.println("true"); //print true
}
else
{
System.out.println("false"); //else print false
}
}
}
I am also attaching the output and code screenshot for your reference.
Output and code screenshot:
#Please don't forget to upvote if you find the solution
helpful. Feel free to ask doubts if any, in the comments section.
Thank you.