What is Prime Number ?
Prime number is a number that is divisible only by itself and 1 (e.g. 2, 3, 5, 7, 11). It is a natural number greater than 1 and is not a product of two smaller natural numbers.
Code :
import java.util.*;public class bonus4 { public static void main(String[] args) { int n, flag = 0; Scanner sc = new Scanner(System.in); System.out.println("Input a Number : "); n = sc.nextInt(); if(n==1 || n==0){ System.out.println("Not a Prime"); } else if(n==2){ System.out.println("Prime"); } else{ for(int i = 2; i<n/2;i++){ if(n%i==0){ flag = 1; break; } } if(flag==0){ System.out.println("Prime"); } else{ System.out.println("Not a Prime"); } } }}
import java.util.*;
public class bonus4 {
public static void main(String[] args) {
int n, flag = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Input a Number : ");
n = sc.nextInt();
if(n==1 || n==0){
System.out.println("Not a Prime");
} else if(n==2){
System.out.println("Prime");
} else{
for(int i = 2; i<n/2;i++){
if(n%i==0){
flag = 1;
break;
}
}
if(flag==0){
System.out.println("Prime");
} else{
System.out.println("Not a Prime");
}
}
}
}
Output :
> Test Case 1 : When 0 or 1 is entered
Enter a number to check :
1
1 is not a prime number
> Test Case 2 : When non prime number is entered
Enter a number to check :
1055
1055 is not a prime number
> Test Case 3 : When prime number is entered
Enter a number to check :
59
59 is a prime number
Explanation :
import java.util.scanner and create a scanner object in main function. Initialize a flag variable as 0. Take a number as a input to check for prime or non prime. Create a if else blook, if statement will check for number 0 or 1. If true then it will print " 'num' is not a prime number " (case 1) and if false else statement is executed. else contains a for loop with 2 as initializer which is iterated till num/2 and is incremented by 1. After this if statement is created with a condition num%i == 0
For a number to be prime this condition should be false so that the if statement outside the for loop is executed (case 3). if the condition is true " 'num' is not a prime number " is printed (case 2) and the value of flag is reassigned as 1 which will make the next if statement false and here it is necessary to use break statement as it will end the loop if the condition is true and avoid unnecessary iteration.
0 Comments
Ask Your Queries in the comments